DataRequest.swift 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  1. //
  2. // DataRequest.swift
  3. //
  4. // Copyright (c) 2014-2024 Alamofire Software Foundation (http://alamofire.org/)
  5. //
  6. // Permission is hereby granted, free of charge, to any person obtaining a copy
  7. // of this software and associated documentation files (the "Software"), to deal
  8. // in the Software without restriction, including without limitation the rights
  9. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. // copies of the Software, and to permit persons to whom the Software is
  11. // furnished to do so, subject to the following conditions:
  12. //
  13. // The above copyright notice and this permission notice shall be included in
  14. // all copies or substantial portions of the Software.
  15. //
  16. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  22. // THE SOFTWARE.
  23. //
  24. import Foundation
  25. /// `Request` subclass which handles in-memory `Data` download using `URLSessionDataTask`.
  26. public class DataRequest: Request {
  27. /// `URLRequestConvertible` value used to create `URLRequest`s for this instance.
  28. public let convertible: URLRequestConvertible
  29. /// `Data` read from the server so far.
  30. public var data: Data? { dataMutableState.data }
  31. private struct DataMutableState {
  32. var data: Data?
  33. var httpResponseHandler: (queue: DispatchQueue,
  34. handler: (_ response: HTTPURLResponse,
  35. _ completionHandler: @escaping (ResponseDisposition) -> Void) -> Void)?
  36. }
  37. private let dataMutableState = Protected(DataMutableState())
  38. /// Creates a `DataRequest` using the provided parameters.
  39. ///
  40. /// - Parameters:
  41. /// - id: `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()` by default.
  42. /// - convertible: `URLRequestConvertible` value used to create `URLRequest`s for this instance.
  43. /// - underlyingQueue: `DispatchQueue` on which all internal `Request` work is performed.
  44. /// - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default targets
  45. /// `underlyingQueue`, but can be passed another queue from a `Session`.
  46. /// - eventMonitor: `EventMonitor` called for event callbacks from internal `Request` actions.
  47. /// - interceptor: `RequestInterceptor` used throughout the request lifecycle.
  48. /// - delegate: `RequestDelegate` that provides an interface to actions not performed by the `Request`.
  49. init(id: UUID = UUID(),
  50. convertible: URLRequestConvertible,
  51. underlyingQueue: DispatchQueue,
  52. serializationQueue: DispatchQueue,
  53. eventMonitor: EventMonitor?,
  54. interceptor: RequestInterceptor?,
  55. delegate: RequestDelegate) {
  56. self.convertible = convertible
  57. super.init(id: id,
  58. underlyingQueue: underlyingQueue,
  59. serializationQueue: serializationQueue,
  60. eventMonitor: eventMonitor,
  61. interceptor: interceptor,
  62. delegate: delegate)
  63. }
  64. override func reset() {
  65. super.reset()
  66. dataMutableState.write { mutableState in
  67. mutableState.data = nil
  68. }
  69. }
  70. /// Called when `Data` is received by this instance.
  71. ///
  72. /// - Note: Also calls `updateDownloadProgress`.
  73. ///
  74. /// - Parameter data: The `Data` received.
  75. func didReceive(data: Data) {
  76. dataMutableState.write { mutableState in
  77. if mutableState.data == nil {
  78. mutableState.data = data
  79. } else {
  80. mutableState.data?.append(data)
  81. }
  82. }
  83. updateDownloadProgress()
  84. }
  85. func didReceiveResponse(_ response: HTTPURLResponse, completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) {
  86. dataMutableState.read { dataMutableState in
  87. guard let httpResponseHandler = dataMutableState.httpResponseHandler else {
  88. underlyingQueue.async { completionHandler(.allow) }
  89. return
  90. }
  91. httpResponseHandler.queue.async {
  92. httpResponseHandler.handler(response) { disposition in
  93. if disposition == .cancel {
  94. self.mutableState.write { mutableState in
  95. mutableState.state = .cancelled
  96. mutableState.error = mutableState.error ?? AFError.explicitlyCancelled
  97. }
  98. }
  99. self.underlyingQueue.async {
  100. completionHandler(disposition.sessionDisposition)
  101. }
  102. }
  103. }
  104. }
  105. }
  106. override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask {
  107. let copiedRequest = request
  108. return session.dataTask(with: copiedRequest)
  109. }
  110. /// Called to update the `downloadProgress` of the instance.
  111. func updateDownloadProgress() {
  112. let totalBytesReceived = Int64(data?.count ?? 0)
  113. let totalBytesExpected = task?.response?.expectedContentLength ?? NSURLSessionTransferSizeUnknown
  114. downloadProgress.totalUnitCount = totalBytesExpected
  115. downloadProgress.completedUnitCount = totalBytesReceived
  116. downloadProgressHandler?.queue.async { self.downloadProgressHandler?.handler(self.downloadProgress) }
  117. }
  118. /// Validates the request, using the specified closure.
  119. ///
  120. /// - Note: If validation fails, subsequent calls to response handlers will have an associated error.
  121. ///
  122. /// - Parameter validation: `Validation` closure used to validate the response.
  123. ///
  124. /// - Returns: The instance.
  125. @discardableResult
  126. public func validate(_ validation: @escaping Validation) -> Self {
  127. let validator: () -> Void = { [unowned self] in
  128. guard error == nil, let response else { return }
  129. let result = validation(request, response, data)
  130. if case let .failure(error) = result { self.error = error.asAFError(or: .responseValidationFailed(reason: .customValidationFailed(error: error))) }
  131. eventMonitor?.request(self,
  132. didValidateRequest: request,
  133. response: response,
  134. data: data,
  135. withResult: result)
  136. }
  137. validators.write { $0.append(validator) }
  138. return self
  139. }
  140. /// Sets a closure called whenever the `DataRequest` produces an `HTTPURLResponse` and providing a completion
  141. /// handler to return a `ResponseDisposition` value.
  142. ///
  143. /// - Parameters:
  144. /// - queue: `DispatchQueue` on which the closure will be called. `.main` by default.
  145. /// - handler: Closure called when the instance produces an `HTTPURLResponse`. The `completionHandler` provided
  146. /// MUST be called, otherwise the request will never complete.
  147. ///
  148. /// - Returns: The instance.
  149. @_disfavoredOverload
  150. @discardableResult
  151. public func onHTTPResponse(
  152. on queue: DispatchQueue = .main,
  153. perform handler: @escaping (_ response: HTTPURLResponse,
  154. _ completionHandler: @escaping (ResponseDisposition) -> Void) -> Void
  155. ) -> Self {
  156. dataMutableState.write { mutableState in
  157. mutableState.httpResponseHandler = (queue, handler)
  158. }
  159. return self
  160. }
  161. /// Sets a closure called whenever the `DataRequest` produces an `HTTPURLResponse`.
  162. ///
  163. /// - Parameters:
  164. /// - queue: `DispatchQueue` on which the closure will be called. `.main` by default.
  165. /// - handler: Closure called when the instance produces an `HTTPURLResponse`.
  166. ///
  167. /// - Returns: The instance.
  168. @discardableResult
  169. public func onHTTPResponse(on queue: DispatchQueue = .main,
  170. perform handler: @escaping (HTTPURLResponse) -> Void) -> Self {
  171. onHTTPResponse(on: queue) { response, completionHandler in
  172. handler(response)
  173. completionHandler(.allow)
  174. }
  175. return self
  176. }
  177. // MARK: Response Serialization
  178. /// Adds a handler to be called once the request has finished.
  179. ///
  180. /// - Parameters:
  181. /// - queue: The queue on which the completion handler is dispatched. `.main` by default.
  182. /// - completionHandler: The code to be executed once the request has finished.
  183. ///
  184. /// - Returns: The request.
  185. @discardableResult
  186. public func response(queue: DispatchQueue = .main, completionHandler: @escaping (AFDataResponse<Data?>) -> Void) -> Self {
  187. appendResponseSerializer {
  188. // Start work that should be on the serialization queue.
  189. let result = AFResult<Data?>(value: self.data, error: self.error)
  190. // End work that should be on the serialization queue.
  191. self.underlyingQueue.async {
  192. let response = DataResponse(request: self.request,
  193. response: self.response,
  194. data: self.data,
  195. metrics: self.metrics,
  196. serializationDuration: 0,
  197. result: result)
  198. self.eventMonitor?.request(self, didParseResponse: response)
  199. self.responseSerializerDidComplete { queue.async { completionHandler(response) } }
  200. }
  201. }
  202. return self
  203. }
  204. private func _response<Serializer: DataResponseSerializerProtocol>(queue: DispatchQueue = .main,
  205. responseSerializer: Serializer,
  206. completionHandler: @escaping (AFDataResponse<Serializer.SerializedObject>) -> Void)
  207. -> Self {
  208. appendResponseSerializer {
  209. // Start work that should be on the serialization queue.
  210. let start = ProcessInfo.processInfo.systemUptime
  211. let result: AFResult<Serializer.SerializedObject> = Result {
  212. try responseSerializer.serialize(request: self.request,
  213. response: self.response,
  214. data: self.data,
  215. error: self.error)
  216. }.mapError { error in
  217. error.asAFError(or: .responseSerializationFailed(reason: .customSerializationFailed(error: error)))
  218. }
  219. let end = ProcessInfo.processInfo.systemUptime
  220. // End work that should be on the serialization queue.
  221. self.underlyingQueue.async {
  222. let response = DataResponse(request: self.request,
  223. response: self.response,
  224. data: self.data,
  225. metrics: self.metrics,
  226. serializationDuration: end - start,
  227. result: result)
  228. self.eventMonitor?.request(self, didParseResponse: response)
  229. guard !self.isCancelled, let serializerError = result.failure, let delegate = self.delegate else {
  230. self.responseSerializerDidComplete { queue.async { completionHandler(response) } }
  231. return
  232. }
  233. delegate.retryResult(for: self, dueTo: serializerError) { retryResult in
  234. var didComplete: (() -> Void)?
  235. defer {
  236. if let didComplete {
  237. self.responseSerializerDidComplete { queue.async { didComplete() } }
  238. }
  239. }
  240. switch retryResult {
  241. case .doNotRetry:
  242. didComplete = { completionHandler(response) }
  243. case let .doNotRetryWithError(retryError):
  244. let result: AFResult<Serializer.SerializedObject> = .failure(retryError.asAFError(orFailWith: "Received retryError was not already AFError"))
  245. let response = DataResponse(request: self.request,
  246. response: self.response,
  247. data: self.data,
  248. metrics: self.metrics,
  249. serializationDuration: end - start,
  250. result: result)
  251. didComplete = { completionHandler(response) }
  252. case .retry, .retryWithDelay:
  253. delegate.retryRequest(self, withDelay: retryResult.delay)
  254. }
  255. }
  256. }
  257. }
  258. return self
  259. }
  260. /// Adds a handler to be called once the request has finished.
  261. ///
  262. /// - Parameters:
  263. /// - queue: The queue on which the completion handler is dispatched. `.main` by default
  264. /// - responseSerializer: The response serializer responsible for serializing the request, response, and data.
  265. /// - completionHandler: The code to be executed once the request has finished.
  266. ///
  267. /// - Returns: The request.
  268. @discardableResult
  269. public func response<Serializer: DataResponseSerializerProtocol>(queue: DispatchQueue = .main,
  270. responseSerializer: Serializer,
  271. completionHandler: @escaping (AFDataResponse<Serializer.SerializedObject>) -> Void)
  272. -> Self {
  273. _response(queue: queue, responseSerializer: responseSerializer, completionHandler: completionHandler)
  274. }
  275. /// Adds a handler to be called once the request has finished.
  276. ///
  277. /// - Parameters:
  278. /// - queue: The queue on which the completion handler is dispatched. `.main` by default
  279. /// - responseSerializer: The response serializer responsible for serializing the request, response, and data.
  280. /// - completionHandler: The code to be executed once the request has finished.
  281. ///
  282. /// - Returns: The request.
  283. @discardableResult
  284. public func response<Serializer: ResponseSerializer>(queue: DispatchQueue = .main,
  285. responseSerializer: Serializer,
  286. completionHandler: @escaping (AFDataResponse<Serializer.SerializedObject>) -> Void)
  287. -> Self {
  288. _response(queue: queue, responseSerializer: responseSerializer, completionHandler: completionHandler)
  289. }
  290. /// Adds a handler using a `DataResponseSerializer` to be called once the request has finished.
  291. ///
  292. /// - Parameters:
  293. /// - queue: The queue on which the completion handler is called. `.main` by default.
  294. /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before calling the
  295. /// `completionHandler`. `PassthroughPreprocessor()` by default.
  296. /// - emptyResponseCodes: HTTP status codes for which empty responses are always valid. `[204, 205]` by default.
  297. /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default.
  298. /// - completionHandler: A closure to be executed once the request has finished.
  299. ///
  300. /// - Returns: The request.
  301. @discardableResult
  302. public func responseData(queue: DispatchQueue = .main,
  303. dataPreprocessor: DataPreprocessor = DataResponseSerializer.defaultDataPreprocessor,
  304. emptyResponseCodes: Set<Int> = DataResponseSerializer.defaultEmptyResponseCodes,
  305. emptyRequestMethods: Set<HTTPMethod> = DataResponseSerializer.defaultEmptyRequestMethods,
  306. completionHandler: @escaping (AFDataResponse<Data>) -> Void) -> Self {
  307. response(queue: queue,
  308. responseSerializer: DataResponseSerializer(dataPreprocessor: dataPreprocessor,
  309. emptyResponseCodes: emptyResponseCodes,
  310. emptyRequestMethods: emptyRequestMethods),
  311. completionHandler: completionHandler)
  312. }
  313. /// Adds a handler using a `StringResponseSerializer` to be called once the request has finished.
  314. ///
  315. /// - Parameters:
  316. /// - queue: The queue on which the completion handler is dispatched. `.main` by default.
  317. /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before calling the
  318. /// `completionHandler`. `PassthroughPreprocessor()` by default.
  319. /// - encoding: The string encoding. Defaults to `nil`, in which case the encoding will be determined
  320. /// from the server response, falling back to the default HTTP character set, `ISO-8859-1`.
  321. /// - emptyResponseCodes: HTTP status codes for which empty responses are always valid. `[204, 205]` by default.
  322. /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default.
  323. /// - completionHandler: A closure to be executed once the request has finished.
  324. ///
  325. /// - Returns: The request.
  326. @discardableResult
  327. public func responseString(queue: DispatchQueue = .main,
  328. dataPreprocessor: DataPreprocessor = StringResponseSerializer.defaultDataPreprocessor,
  329. encoding: String.Encoding? = nil,
  330. emptyResponseCodes: Set<Int> = StringResponseSerializer.defaultEmptyResponseCodes,
  331. emptyRequestMethods: Set<HTTPMethod> = StringResponseSerializer.defaultEmptyRequestMethods,
  332. completionHandler: @escaping (AFDataResponse<String>) -> Void) -> Self {
  333. response(queue: queue,
  334. responseSerializer: StringResponseSerializer(dataPreprocessor: dataPreprocessor,
  335. encoding: encoding,
  336. emptyResponseCodes: emptyResponseCodes,
  337. emptyRequestMethods: emptyRequestMethods),
  338. completionHandler: completionHandler)
  339. }
  340. /// Adds a handler using a `JSONResponseSerializer` to be called once the request has finished.
  341. ///
  342. /// - Parameters:
  343. /// - queue: The queue on which the completion handler is dispatched. `.main` by default.
  344. /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before calling the
  345. /// `completionHandler`. `PassthroughPreprocessor()` by default.
  346. /// - emptyResponseCodes: HTTP status codes for which empty responses are always valid. `[204, 205]` by default.
  347. /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default.
  348. /// - options: `JSONSerialization.ReadingOptions` used when parsing the response. `.allowFragments`
  349. /// by default.
  350. /// - completionHandler: A closure to be executed once the request has finished.
  351. ///
  352. /// - Returns: The request.
  353. @available(*, deprecated, message: "responseJSON deprecated and will be removed in Alamofire 6. Use responseDecodable instead.")
  354. @discardableResult
  355. public func responseJSON(queue: DispatchQueue = .main,
  356. dataPreprocessor: DataPreprocessor = JSONResponseSerializer.defaultDataPreprocessor,
  357. emptyResponseCodes: Set<Int> = JSONResponseSerializer.defaultEmptyResponseCodes,
  358. emptyRequestMethods: Set<HTTPMethod> = JSONResponseSerializer.defaultEmptyRequestMethods,
  359. options: JSONSerialization.ReadingOptions = .allowFragments,
  360. completionHandler: @escaping (AFDataResponse<Any>) -> Void) -> Self {
  361. response(queue: queue,
  362. responseSerializer: JSONResponseSerializer(dataPreprocessor: dataPreprocessor,
  363. emptyResponseCodes: emptyResponseCodes,
  364. emptyRequestMethods: emptyRequestMethods,
  365. options: options),
  366. completionHandler: completionHandler)
  367. }
  368. /// Adds a handler using a `DecodableResponseSerializer` to be called once the request has finished.
  369. ///
  370. /// - Parameters:
  371. /// - type: `Decodable` type to decode from response data.
  372. /// - queue: The queue on which the completion handler is dispatched. `.main` by default.
  373. /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before calling the
  374. /// `completionHandler`. `PassthroughPreprocessor()` by default.
  375. /// - decoder: `DataDecoder` to use to decode the response. `JSONDecoder()` by default.
  376. /// - emptyResponseCodes: HTTP status codes for which empty responses are always valid. `[204, 205]` by default.
  377. /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default.
  378. /// - completionHandler: A closure to be executed once the request has finished.
  379. ///
  380. /// - Returns: The request.
  381. @discardableResult
  382. public func responseDecodable<T: Decodable>(of type: T.Type = T.self,
  383. queue: DispatchQueue = .main,
  384. dataPreprocessor: DataPreprocessor = DecodableResponseSerializer<T>.defaultDataPreprocessor,
  385. decoder: DataDecoder = JSONDecoder(),
  386. emptyResponseCodes: Set<Int> = DecodableResponseSerializer<T>.defaultEmptyResponseCodes,
  387. emptyRequestMethods: Set<HTTPMethod> = DecodableResponseSerializer<T>.defaultEmptyRequestMethods,
  388. completionHandler: @escaping (AFDataResponse<T>) -> Void) -> Self {
  389. response(queue: queue,
  390. responseSerializer: DecodableResponseSerializer(dataPreprocessor: dataPreprocessor,
  391. decoder: decoder,
  392. emptyResponseCodes: emptyResponseCodes,
  393. emptyRequestMethods: emptyRequestMethods),
  394. completionHandler: completionHandler)
  395. }
  396. }