DownloadRequest.swift 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588
  1. //
  2. // DownloadRequest.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 downloads `Data` to a file on disk using `URLSessionDownloadTask`.
  26. public final class DownloadRequest: Request {
  27. /// A set of options to be executed prior to moving a downloaded file from the temporary `URL` to the destination
  28. /// `URL`.
  29. public struct Options: OptionSet {
  30. /// Specifies that intermediate directories for the destination URL should be created.
  31. public static let createIntermediateDirectories = Options(rawValue: 1 << 0)
  32. /// Specifies that any previous file at the destination `URL` should be removed.
  33. public static let removePreviousFile = Options(rawValue: 1 << 1)
  34. public let rawValue: Int
  35. public init(rawValue: Int) {
  36. self.rawValue = rawValue
  37. }
  38. }
  39. // MARK: Destination
  40. /// A closure executed once a `DownloadRequest` has successfully completed in order to determine where to move the
  41. /// temporary file written to during the download process. The closure takes two arguments: the temporary file URL
  42. /// and the `HTTPURLResponse`, and returns two values: the file URL where the temporary file should be moved and
  43. /// the options defining how the file should be moved.
  44. ///
  45. /// - Note: Downloads from a local `file://` `URL`s do not use the `Destination` closure, as those downloads do not
  46. /// return an `HTTPURLResponse`. Instead the file is merely moved within the temporary directory.
  47. public typealias Destination = (_ temporaryURL: URL,
  48. _ response: HTTPURLResponse) -> (destinationURL: URL, options: Options)
  49. /// Creates a download file destination closure which uses the default file manager to move the temporary file to a
  50. /// file URL in the first available directory with the specified search path directory and search path domain mask.
  51. ///
  52. /// - Parameters:
  53. /// - directory: The search path directory. `.documentDirectory` by default.
  54. /// - domain: The search path domain mask. `.userDomainMask` by default.
  55. /// - options: `DownloadRequest.Options` used when moving the downloaded file to its destination. None by
  56. /// default.
  57. /// - Returns: The `Destination` closure.
  58. public class func suggestedDownloadDestination(for directory: FileManager.SearchPathDirectory = .documentDirectory,
  59. in domain: FileManager.SearchPathDomainMask = .userDomainMask,
  60. options: Options = []) -> Destination {
  61. { temporaryURL, response in
  62. let directoryURLs = FileManager.default.urls(for: directory, in: domain)
  63. let url = directoryURLs.first?.appendingPathComponent(response.suggestedFilename!) ?? temporaryURL
  64. return (url, options)
  65. }
  66. }
  67. /// Default `Destination` used by Alamofire to ensure all downloads persist. This `Destination` prepends
  68. /// `Alamofire_` to the automatically generated download name and moves it within the temporary directory. Files
  69. /// with this destination must be additionally moved if they should survive the system reclamation of temporary
  70. /// space.
  71. static let defaultDestination: Destination = { url, _ in
  72. (defaultDestinationURL(url), [])
  73. }
  74. /// Default `URL` creation closure. Creates a `URL` in the temporary directory with `Alamofire_` prepended to the
  75. /// provided file name.
  76. static let defaultDestinationURL: (URL) -> URL = { url in
  77. let filename = "Alamofire_\(url.lastPathComponent)"
  78. let destination = url.deletingLastPathComponent().appendingPathComponent(filename)
  79. return destination
  80. }
  81. // MARK: Downloadable
  82. /// Type describing the source used to create the underlying `URLSessionDownloadTask`.
  83. public enum Downloadable {
  84. /// Download should be started from the `URLRequest` produced by the associated `URLRequestConvertible` value.
  85. case request(URLRequestConvertible)
  86. /// Download should be started from the associated resume `Data` value.
  87. case resumeData(Data)
  88. }
  89. // MARK: Mutable State
  90. /// Type containing all mutable state for `DownloadRequest` instances.
  91. private struct DownloadRequestMutableState {
  92. /// Possible resume `Data` produced when cancelling the instance.
  93. var resumeData: Data?
  94. /// `URL` to which `Data` is being downloaded.
  95. var fileURL: URL?
  96. }
  97. /// Protected mutable state specific to `DownloadRequest`.
  98. private let mutableDownloadState = Protected(DownloadRequestMutableState())
  99. /// If the download is resumable and is eventually cancelled or fails, this value may be used to resume the download
  100. /// using the `download(resumingWith data:)` API.
  101. ///
  102. /// - Note: For more information about `resumeData`, see [Apple's documentation](https://developer.apple.com/documentation/foundation/urlsessiondownloadtask/1411634-cancel).
  103. public var resumeData: Data? {
  104. #if !canImport(FoundationNetworking) // If we not using swift-corelibs-foundation.
  105. return mutableDownloadState.resumeData ?? error?.downloadResumeData
  106. #else
  107. return mutableDownloadState.resumeData
  108. #endif
  109. }
  110. /// If the download is successful, the `URL` where the file was downloaded.
  111. public var fileURL: URL? { mutableDownloadState.fileURL }
  112. // MARK: Initial State
  113. /// `Downloadable` value used for this instance.
  114. public let downloadable: Downloadable
  115. /// The `Destination` to which the downloaded file is moved.
  116. let destination: Destination
  117. /// Creates a `DownloadRequest` using the provided parameters.
  118. ///
  119. /// - Parameters:
  120. /// - id: `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()` by default.
  121. /// - downloadable: `Downloadable` value used to create `URLSessionDownloadTasks` for the instance.
  122. /// - underlyingQueue: `DispatchQueue` on which all internal `Request` work is performed.
  123. /// - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default targets
  124. /// `underlyingQueue`, but can be passed another queue from a `Session`.
  125. /// - eventMonitor: `EventMonitor` called for event callbacks from internal `Request` actions.
  126. /// - interceptor: `RequestInterceptor` used throughout the request lifecycle.
  127. /// - delegate: `RequestDelegate` that provides an interface to actions not performed by the `Request`
  128. /// - destination: `Destination` closure used to move the downloaded file to its final location.
  129. init(id: UUID = UUID(),
  130. downloadable: Downloadable,
  131. underlyingQueue: DispatchQueue,
  132. serializationQueue: DispatchQueue,
  133. eventMonitor: EventMonitor?,
  134. interceptor: RequestInterceptor?,
  135. delegate: RequestDelegate,
  136. destination: @escaping Destination) {
  137. self.downloadable = downloadable
  138. self.destination = destination
  139. super.init(id: id,
  140. underlyingQueue: underlyingQueue,
  141. serializationQueue: serializationQueue,
  142. eventMonitor: eventMonitor,
  143. interceptor: interceptor,
  144. delegate: delegate)
  145. }
  146. override func reset() {
  147. super.reset()
  148. mutableDownloadState.write {
  149. $0.resumeData = nil
  150. $0.fileURL = nil
  151. }
  152. }
  153. /// Called when a download has finished.
  154. ///
  155. /// - Parameters:
  156. /// - task: `URLSessionTask` that finished the download.
  157. /// - result: `Result` of the automatic move to `destination`.
  158. func didFinishDownloading(using task: URLSessionTask, with result: Result<URL, AFError>) {
  159. eventMonitor?.request(self, didFinishDownloadingUsing: task, with: result)
  160. switch result {
  161. case let .success(url): mutableDownloadState.fileURL = url
  162. case let .failure(error): self.error = error
  163. }
  164. }
  165. /// Updates the `downloadProgress` using the provided values.
  166. ///
  167. /// - Parameters:
  168. /// - bytesWritten: Total bytes written so far.
  169. /// - totalBytesExpectedToWrite: Total bytes expected to write.
  170. func updateDownloadProgress(bytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
  171. downloadProgress.totalUnitCount = totalBytesExpectedToWrite
  172. downloadProgress.completedUnitCount += bytesWritten
  173. downloadProgressHandler?.queue.async { self.downloadProgressHandler?.handler(self.downloadProgress) }
  174. }
  175. override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask {
  176. session.downloadTask(with: request)
  177. }
  178. /// Creates a `URLSessionTask` from the provided resume data.
  179. ///
  180. /// - Parameters:
  181. /// - data: `Data` used to resume the download.
  182. /// - session: `URLSession` used to create the `URLSessionTask`.
  183. ///
  184. /// - Returns: The `URLSessionTask` created.
  185. public func task(forResumeData data: Data, using session: URLSession) -> URLSessionTask {
  186. session.downloadTask(withResumeData: data)
  187. }
  188. /// Cancels the instance. Once cancelled, a `DownloadRequest` can no longer be resumed or suspended.
  189. ///
  190. /// - Note: This method will NOT produce resume data. If you wish to cancel and produce resume data, use
  191. /// `cancel(producingResumeData:)` or `cancel(byProducingResumeData:)`.
  192. ///
  193. /// - Returns: The instance.
  194. @discardableResult
  195. override public func cancel() -> Self {
  196. cancel(producingResumeData: false)
  197. }
  198. /// Cancels the instance, optionally producing resume data. Once cancelled, a `DownloadRequest` can no longer be
  199. /// resumed or suspended.
  200. ///
  201. /// - Note: If `producingResumeData` is `true`, the `resumeData` property will be populated with any resume data, if
  202. /// available.
  203. ///
  204. /// - Returns: The instance.
  205. @discardableResult
  206. public func cancel(producingResumeData shouldProduceResumeData: Bool) -> Self {
  207. cancel(optionallyProducingResumeData: shouldProduceResumeData ? { _ in } : nil)
  208. }
  209. /// Cancels the instance while producing resume data. Once cancelled, a `DownloadRequest` can no longer be resumed
  210. /// or suspended.
  211. ///
  212. /// - Note: The resume data passed to the completion handler will also be available on the instance's `resumeData`
  213. /// property.
  214. ///
  215. /// - Parameter completionHandler: The completion handler that is called when the download has been successfully
  216. /// cancelled. It is not guaranteed to be called on a particular queue, so you may
  217. /// want use an appropriate queue to perform your work.
  218. ///
  219. /// - Returns: The instance.
  220. @discardableResult
  221. public func cancel(byProducingResumeData completionHandler: @escaping (_ data: Data?) -> Void) -> Self {
  222. cancel(optionallyProducingResumeData: completionHandler)
  223. }
  224. /// Internal implementation of cancellation that optionally takes a resume data handler. If no handler is passed,
  225. /// cancellation is performed without producing resume data.
  226. ///
  227. /// - Parameter completionHandler: Optional resume data handler.
  228. ///
  229. /// - Returns: The instance.
  230. private func cancel(optionallyProducingResumeData completionHandler: ((_ resumeData: Data?) -> Void)?) -> Self {
  231. mutableState.write { mutableState in
  232. guard mutableState.state.canTransitionTo(.cancelled) else { return }
  233. mutableState.state = .cancelled
  234. underlyingQueue.async { self.didCancel() }
  235. guard let task = mutableState.tasks.last as? URLSessionDownloadTask, task.state != .completed else {
  236. underlyingQueue.async { self.finish() }
  237. return
  238. }
  239. if let completionHandler {
  240. // Resume to ensure metrics are gathered.
  241. task.resume()
  242. task.cancel { resumeData in
  243. self.mutableDownloadState.resumeData = resumeData
  244. self.underlyingQueue.async { self.didCancelTask(task) }
  245. completionHandler(resumeData)
  246. }
  247. } else {
  248. // Resume to ensure metrics are gathered.
  249. task.resume()
  250. task.cancel()
  251. self.underlyingQueue.async { self.didCancelTask(task) }
  252. }
  253. }
  254. return self
  255. }
  256. /// Validates the request, using the specified closure.
  257. ///
  258. /// - Note: If validation fails, subsequent calls to response handlers will have an associated error.
  259. ///
  260. /// - Parameter validation: `Validation` closure to validate the response.
  261. ///
  262. /// - Returns: The instance.
  263. @discardableResult
  264. public func validate(_ validation: @escaping Validation) -> Self {
  265. let validator: () -> Void = { [unowned self] in
  266. guard error == nil, let response else { return }
  267. let result = validation(request, response, fileURL)
  268. if case let .failure(error) = result {
  269. self.error = error.asAFError(or: .responseValidationFailed(reason: .customValidationFailed(error: error)))
  270. }
  271. eventMonitor?.request(self,
  272. didValidateRequest: request,
  273. response: response,
  274. fileURL: fileURL,
  275. withResult: result)
  276. }
  277. validators.write { $0.append(validator) }
  278. return self
  279. }
  280. // MARK: - Response Serialization
  281. /// Adds a handler to be called once the request has finished.
  282. ///
  283. /// - Parameters:
  284. /// - queue: The queue on which the completion handler is dispatched. `.main` by default.
  285. /// - completionHandler: The code to be executed once the request has finished.
  286. ///
  287. /// - Returns: The request.
  288. @discardableResult
  289. public func response(queue: DispatchQueue = .main,
  290. completionHandler: @escaping (AFDownloadResponse<URL?>) -> Void)
  291. -> Self {
  292. appendResponseSerializer {
  293. // Start work that should be on the serialization queue.
  294. let result = AFResult<URL?>(value: self.fileURL, error: self.error)
  295. // End work that should be on the serialization queue.
  296. self.underlyingQueue.async {
  297. let response = DownloadResponse(request: self.request,
  298. response: self.response,
  299. fileURL: self.fileURL,
  300. resumeData: self.resumeData,
  301. metrics: self.metrics,
  302. serializationDuration: 0,
  303. result: result)
  304. self.eventMonitor?.request(self, didParseResponse: response)
  305. self.responseSerializerDidComplete { queue.async { completionHandler(response) } }
  306. }
  307. }
  308. return self
  309. }
  310. private func _response<Serializer: DownloadResponseSerializerProtocol>(queue: DispatchQueue = .main,
  311. responseSerializer: Serializer,
  312. completionHandler: @escaping (AFDownloadResponse<Serializer.SerializedObject>) -> Void)
  313. -> Self {
  314. appendResponseSerializer {
  315. // Start work that should be on the serialization queue.
  316. let start = ProcessInfo.processInfo.systemUptime
  317. let result: AFResult<Serializer.SerializedObject> = Result {
  318. try responseSerializer.serializeDownload(request: self.request,
  319. response: self.response,
  320. fileURL: self.fileURL,
  321. error: self.error)
  322. }.mapError { error in
  323. error.asAFError(or: .responseSerializationFailed(reason: .customSerializationFailed(error: error)))
  324. }
  325. let end = ProcessInfo.processInfo.systemUptime
  326. // End work that should be on the serialization queue.
  327. self.underlyingQueue.async {
  328. let response = DownloadResponse(request: self.request,
  329. response: self.response,
  330. fileURL: self.fileURL,
  331. resumeData: self.resumeData,
  332. metrics: self.metrics,
  333. serializationDuration: end - start,
  334. result: result)
  335. self.eventMonitor?.request(self, didParseResponse: response)
  336. guard let serializerError = result.failure, let delegate = self.delegate else {
  337. self.responseSerializerDidComplete { queue.async { completionHandler(response) } }
  338. return
  339. }
  340. delegate.retryResult(for: self, dueTo: serializerError) { retryResult in
  341. var didComplete: (() -> Void)?
  342. defer {
  343. if let didComplete {
  344. self.responseSerializerDidComplete { queue.async { didComplete() } }
  345. }
  346. }
  347. switch retryResult {
  348. case .doNotRetry:
  349. didComplete = { completionHandler(response) }
  350. case let .doNotRetryWithError(retryError):
  351. let result: AFResult<Serializer.SerializedObject> = .failure(retryError.asAFError(orFailWith: "Received retryError was not already AFError"))
  352. let response = DownloadResponse(request: self.request,
  353. response: self.response,
  354. fileURL: self.fileURL,
  355. resumeData: self.resumeData,
  356. metrics: self.metrics,
  357. serializationDuration: end - start,
  358. result: result)
  359. didComplete = { completionHandler(response) }
  360. case .retry, .retryWithDelay:
  361. delegate.retryRequest(self, withDelay: retryResult.delay)
  362. }
  363. }
  364. }
  365. }
  366. return self
  367. }
  368. /// Adds a handler to be called once the request has finished.
  369. ///
  370. /// - Parameters:
  371. /// - queue: The queue on which the completion handler is dispatched. `.main` by default.
  372. /// - responseSerializer: The response serializer responsible for serializing the request, response, and data
  373. /// contained in the destination `URL`.
  374. /// - completionHandler: The code to be executed once the request has finished.
  375. ///
  376. /// - Returns: The request.
  377. @discardableResult
  378. public func response<Serializer: DownloadResponseSerializerProtocol>(queue: DispatchQueue = .main,
  379. responseSerializer: Serializer,
  380. completionHandler: @escaping (AFDownloadResponse<Serializer.SerializedObject>) -> Void)
  381. -> Self {
  382. _response(queue: queue, responseSerializer: responseSerializer, completionHandler: completionHandler)
  383. }
  384. /// Adds a handler to be called once the request has finished.
  385. ///
  386. /// - Parameters:
  387. /// - queue: The queue on which the completion handler is dispatched. `.main` by default.
  388. /// - responseSerializer: The response serializer responsible for serializing the request, response, and data
  389. /// contained in the destination `URL`.
  390. /// - completionHandler: The code to be executed once the request has finished.
  391. ///
  392. /// - Returns: The request.
  393. @discardableResult
  394. public func response<Serializer: ResponseSerializer>(queue: DispatchQueue = .main,
  395. responseSerializer: Serializer,
  396. completionHandler: @escaping (AFDownloadResponse<Serializer.SerializedObject>) -> Void)
  397. -> Self {
  398. _response(queue: queue, responseSerializer: responseSerializer, completionHandler: completionHandler)
  399. }
  400. /// Adds a handler using a `URLResponseSerializer` to be called once the request is finished.
  401. ///
  402. /// - Parameters:
  403. /// - queue: The queue on which the completion handler is called. `.main` by default.
  404. /// - completionHandler: A closure to be executed once the request has finished.
  405. ///
  406. /// - Returns: The request.
  407. @discardableResult
  408. public func responseURL(queue: DispatchQueue = .main,
  409. completionHandler: @escaping (AFDownloadResponse<URL>) -> Void) -> Self {
  410. response(queue: queue, responseSerializer: URLResponseSerializer(), completionHandler: completionHandler)
  411. }
  412. /// Adds a handler using a `DataResponseSerializer` to be called once the request has finished.
  413. ///
  414. /// - Parameters:
  415. /// - queue: The queue on which the completion handler is called. `.main` by default.
  416. /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before calling the
  417. /// `completionHandler`. `PassthroughPreprocessor()` by default.
  418. /// - emptyResponseCodes: HTTP status codes for which empty responses are always valid. `[204, 205]` by default.
  419. /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default.
  420. /// - completionHandler: A closure to be executed once the request has finished.
  421. ///
  422. /// - Returns: The request.
  423. @discardableResult
  424. public func responseData(queue: DispatchQueue = .main,
  425. dataPreprocessor: DataPreprocessor = DataResponseSerializer.defaultDataPreprocessor,
  426. emptyResponseCodes: Set<Int> = DataResponseSerializer.defaultEmptyResponseCodes,
  427. emptyRequestMethods: Set<HTTPMethod> = DataResponseSerializer.defaultEmptyRequestMethods,
  428. completionHandler: @escaping (AFDownloadResponse<Data>) -> Void) -> Self {
  429. response(queue: queue,
  430. responseSerializer: DataResponseSerializer(dataPreprocessor: dataPreprocessor,
  431. emptyResponseCodes: emptyResponseCodes,
  432. emptyRequestMethods: emptyRequestMethods),
  433. completionHandler: completionHandler)
  434. }
  435. /// Adds a handler using a `StringResponseSerializer` to be called once the request has finished.
  436. ///
  437. /// - Parameters:
  438. /// - queue: The queue on which the completion handler is dispatched. `.main` by default.
  439. /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before calling the
  440. /// `completionHandler`. `PassthroughPreprocessor()` by default.
  441. /// - encoding: The string encoding. Defaults to `nil`, in which case the encoding will be determined
  442. /// from the server response, falling back to the default HTTP character set, `ISO-8859-1`.
  443. /// - emptyResponseCodes: HTTP status codes for which empty responses are always valid. `[204, 205]` by default.
  444. /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default.
  445. /// - completionHandler: A closure to be executed once the request has finished.
  446. ///
  447. /// - Returns: The request.
  448. @discardableResult
  449. public func responseString(queue: DispatchQueue = .main,
  450. dataPreprocessor: DataPreprocessor = StringResponseSerializer.defaultDataPreprocessor,
  451. encoding: String.Encoding? = nil,
  452. emptyResponseCodes: Set<Int> = StringResponseSerializer.defaultEmptyResponseCodes,
  453. emptyRequestMethods: Set<HTTPMethod> = StringResponseSerializer.defaultEmptyRequestMethods,
  454. completionHandler: @escaping (AFDownloadResponse<String>) -> Void) -> Self {
  455. response(queue: queue,
  456. responseSerializer: StringResponseSerializer(dataPreprocessor: dataPreprocessor,
  457. encoding: encoding,
  458. emptyResponseCodes: emptyResponseCodes,
  459. emptyRequestMethods: emptyRequestMethods),
  460. completionHandler: completionHandler)
  461. }
  462. /// Adds a handler using a `JSONResponseSerializer` to be called once the request has finished.
  463. ///
  464. /// - Parameters:
  465. /// - queue: The queue on which the completion handler is dispatched. `.main` by default.
  466. /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before calling the
  467. /// `completionHandler`. `PassthroughPreprocessor()` by default.
  468. /// - emptyResponseCodes: HTTP status codes for which empty responses are always valid. `[204, 205]` by default.
  469. /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default.
  470. /// - options: `JSONSerialization.ReadingOptions` used when parsing the response. `.allowFragments`
  471. /// by default.
  472. /// - completionHandler: A closure to be executed once the request has finished.
  473. ///
  474. /// - Returns: The request.
  475. @available(*, deprecated, message: "responseJSON deprecated and will be removed in Alamofire 6. Use responseDecodable instead.")
  476. @discardableResult
  477. public func responseJSON(queue: DispatchQueue = .main,
  478. dataPreprocessor: DataPreprocessor = JSONResponseSerializer.defaultDataPreprocessor,
  479. emptyResponseCodes: Set<Int> = JSONResponseSerializer.defaultEmptyResponseCodes,
  480. emptyRequestMethods: Set<HTTPMethod> = JSONResponseSerializer.defaultEmptyRequestMethods,
  481. options: JSONSerialization.ReadingOptions = .allowFragments,
  482. completionHandler: @escaping (AFDownloadResponse<Any>) -> Void) -> Self {
  483. response(queue: queue,
  484. responseSerializer: JSONResponseSerializer(dataPreprocessor: dataPreprocessor,
  485. emptyResponseCodes: emptyResponseCodes,
  486. emptyRequestMethods: emptyRequestMethods,
  487. options: options),
  488. completionHandler: completionHandler)
  489. }
  490. /// Adds a handler using a `DecodableResponseSerializer` to be called once the request has finished.
  491. ///
  492. /// - Parameters:
  493. /// - type: `Decodable` type to decode from response data.
  494. /// - queue: The queue on which the completion handler is dispatched. `.main` by default.
  495. /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before calling the
  496. /// `completionHandler`. `PassthroughPreprocessor()` by default.
  497. /// - decoder: `DataDecoder` to use to decode the response. `JSONDecoder()` by default.
  498. /// - emptyResponseCodes: HTTP status codes for which empty responses are always valid. `[204, 205]` by default.
  499. /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default.
  500. /// - completionHandler: A closure to be executed once the request has finished.
  501. ///
  502. /// - Returns: The request.
  503. @discardableResult
  504. public func responseDecodable<T: Decodable>(of type: T.Type = T.self,
  505. queue: DispatchQueue = .main,
  506. dataPreprocessor: DataPreprocessor = DecodableResponseSerializer<T>.defaultDataPreprocessor,
  507. decoder: DataDecoder = JSONDecoder(),
  508. emptyResponseCodes: Set<Int> = DecodableResponseSerializer<T>.defaultEmptyResponseCodes,
  509. emptyRequestMethods: Set<HTTPMethod> = DecodableResponseSerializer<T>.defaultEmptyRequestMethods,
  510. completionHandler: @escaping (AFDownloadResponse<T>) -> Void) -> Self {
  511. response(queue: queue,
  512. responseSerializer: DecodableResponseSerializer(dataPreprocessor: dataPreprocessor,
  513. decoder: decoder,
  514. emptyResponseCodes: emptyResponseCodes,
  515. emptyRequestMethods: emptyRequestMethods),
  516. completionHandler: completionHandler)
  517. }
  518. }