2
0

DownloadRequest.swift 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607
  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, @unchecked Sendable {
  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, Sendable {
  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 = @Sendable (_ 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: @Sendable (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(any 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: (any EventMonitor)?,
  134. interceptor: (any RequestInterceptor)?,
  135. delegate: any 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 ? { @Sendable _ 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. @preconcurrency
  221. @discardableResult
  222. public func cancel(byProducingResumeData completionHandler: @Sendable @escaping (_ data: Data?) -> Void) -> Self {
  223. cancel(optionallyProducingResumeData: completionHandler)
  224. }
  225. /// Internal implementation of cancellation that optionally takes a resume data handler. If no handler is passed,
  226. /// cancellation is performed without producing resume data.
  227. ///
  228. /// - Parameter completionHandler: Optional resume data handler.
  229. ///
  230. /// - Returns: The instance.
  231. private func cancel(optionallyProducingResumeData completionHandler: (@Sendable (_ resumeData: Data?) -> Void)?) -> Self {
  232. mutableState.write { mutableState in
  233. guard mutableState.state.canTransitionTo(.cancelled) else { return }
  234. mutableState.state = .cancelled
  235. underlyingQueue.async { self.didCancel() }
  236. guard let task = mutableState.tasks.last as? URLSessionDownloadTask, task.state != .completed else {
  237. underlyingQueue.async { self.finish() }
  238. return
  239. }
  240. if let completionHandler {
  241. // Resume to ensure metrics are gathered.
  242. task.resume()
  243. task.cancel { resumeData in
  244. self.mutableDownloadState.resumeData = resumeData
  245. self.underlyingQueue.async { self.didCancelTask(task) }
  246. completionHandler(resumeData)
  247. }
  248. } else {
  249. // Resume to ensure metrics are gathered.
  250. task.resume()
  251. task.cancel()
  252. self.underlyingQueue.async { self.didCancelTask(task) }
  253. }
  254. }
  255. return self
  256. }
  257. /// Validates the request, using the specified closure.
  258. ///
  259. /// - Note: If validation fails, subsequent calls to response handlers will have an associated error.
  260. ///
  261. /// - Parameter validation: `Validation` closure to validate the response.
  262. ///
  263. /// - Returns: The instance.
  264. @discardableResult
  265. public func validate(_ validation: @escaping Validation) -> Self {
  266. let validator: () -> Void = { [unowned self] in
  267. guard error == nil, let response else { return }
  268. let result = validation(request, response, fileURL)
  269. if case let .failure(error) = result {
  270. self.error = error.asAFError(or: .responseValidationFailed(reason: .customValidationFailed(error: error)))
  271. }
  272. eventMonitor?.request(self,
  273. didValidateRequest: request,
  274. response: response,
  275. fileURL: fileURL,
  276. withResult: result)
  277. }
  278. validators.write { $0.append(validator) }
  279. return self
  280. }
  281. // MARK: - Response Serialization
  282. /// Adds a handler to be called once the request has finished.
  283. ///
  284. /// - Parameters:
  285. /// - queue: The queue on which the completion handler is dispatched. `.main` by default.
  286. /// - completionHandler: The code to be executed once the request has finished.
  287. ///
  288. /// - Returns: The request.
  289. @preconcurrency
  290. @discardableResult
  291. public func response(queue: DispatchQueue = .main,
  292. completionHandler: @Sendable @escaping (AFDownloadResponse<URL?>) -> Void)
  293. -> Self {
  294. appendResponseSerializer {
  295. // Start work that should be on the serialization queue.
  296. let result = AFResult<URL?>(value: self.fileURL, error: self.error)
  297. // End work that should be on the serialization queue.
  298. self.underlyingQueue.async {
  299. let response = DownloadResponse(request: self.request,
  300. response: self.response,
  301. fileURL: self.fileURL,
  302. resumeData: self.resumeData,
  303. metrics: self.metrics,
  304. serializationDuration: 0,
  305. result: result)
  306. self.eventMonitor?.request(self, didParseResponse: response)
  307. self.responseSerializerDidComplete { queue.async { completionHandler(response) } }
  308. }
  309. }
  310. return self
  311. }
  312. private func _response<Serializer: DownloadResponseSerializerProtocol>(queue: DispatchQueue = .main,
  313. responseSerializer: Serializer,
  314. completionHandler: @Sendable @escaping (AFDownloadResponse<Serializer.SerializedObject>) -> Void)
  315. -> Self {
  316. appendResponseSerializer {
  317. // Start work that should be on the serialization queue.
  318. let start = ProcessInfo.processInfo.systemUptime
  319. let result: AFResult<Serializer.SerializedObject> = Result {
  320. try responseSerializer.serializeDownload(request: self.request,
  321. response: self.response,
  322. fileURL: self.fileURL,
  323. error: self.error)
  324. }.mapError { error in
  325. error.asAFError(or: .responseSerializationFailed(reason: .customSerializationFailed(error: error)))
  326. }
  327. let end = ProcessInfo.processInfo.systemUptime
  328. // End work that should be on the serialization queue.
  329. self.underlyingQueue.async {
  330. let response = DownloadResponse(request: self.request,
  331. response: self.response,
  332. fileURL: self.fileURL,
  333. resumeData: self.resumeData,
  334. metrics: self.metrics,
  335. serializationDuration: end - start,
  336. result: result)
  337. self.eventMonitor?.request(self, didParseResponse: response)
  338. guard let serializerError = result.failure, let delegate = self.delegate else {
  339. self.responseSerializerDidComplete { queue.async { completionHandler(response) } }
  340. return
  341. }
  342. delegate.retryResult(for: self, dueTo: serializerError) { retryResult in
  343. var didComplete: (@Sendable () -> Void)?
  344. defer {
  345. if let didComplete {
  346. self.responseSerializerDidComplete { queue.async { didComplete() } }
  347. }
  348. }
  349. switch retryResult {
  350. case .doNotRetry:
  351. didComplete = { completionHandler(response) }
  352. case let .doNotRetryWithError(retryError):
  353. let result: AFResult<Serializer.SerializedObject> = .failure(retryError.asAFError(orFailWith: "Received retryError was not already AFError"))
  354. let response = DownloadResponse(request: self.request,
  355. response: self.response,
  356. fileURL: self.fileURL,
  357. resumeData: self.resumeData,
  358. metrics: self.metrics,
  359. serializationDuration: end - start,
  360. result: result)
  361. didComplete = { completionHandler(response) }
  362. case .retry, .retryWithDelay:
  363. delegate.retryRequest(self, withDelay: retryResult.delay)
  364. }
  365. }
  366. }
  367. }
  368. return self
  369. }
  370. /// Adds a handler to be called once the request has finished.
  371. ///
  372. /// - Note: This handler will read the entire downloaded file into memory, use with caution.
  373. ///
  374. /// - Parameters:
  375. /// - queue: The queue on which the completion handler is dispatched. `.main` by default.
  376. /// - responseSerializer: The response serializer responsible for serializing the request, response, and data
  377. /// contained in the destination `URL`.
  378. /// - completionHandler: The code to be executed once the request has finished.
  379. ///
  380. /// - Returns: The request.
  381. @discardableResult
  382. public func response<Serializer: DownloadResponseSerializerProtocol>(queue: DispatchQueue = .main,
  383. responseSerializer: Serializer,
  384. completionHandler: @Sendable @escaping (AFDownloadResponse<Serializer.SerializedObject>) -> Void)
  385. -> Self {
  386. _response(queue: queue, responseSerializer: responseSerializer, completionHandler: completionHandler)
  387. }
  388. /// Adds a handler to be called once the request has finished.
  389. ///
  390. /// - Note: This handler will read the entire downloaded file into memory, use with caution.
  391. ///
  392. /// - Parameters:
  393. /// - queue: The queue on which the completion handler is dispatched. `.main` by default.
  394. /// - responseSerializer: The response serializer responsible for serializing the request, response, and data
  395. /// contained in the destination `URL`.
  396. /// - completionHandler: The code to be executed once the request has finished.
  397. ///
  398. /// - Returns: The request.
  399. @discardableResult
  400. public func response<Serializer: ResponseSerializer>(queue: DispatchQueue = .main,
  401. responseSerializer: Serializer,
  402. completionHandler: @Sendable @escaping (AFDownloadResponse<Serializer.SerializedObject>) -> Void)
  403. -> Self {
  404. _response(queue: queue, responseSerializer: responseSerializer, completionHandler: completionHandler)
  405. }
  406. /// Adds a handler using a `URLResponseSerializer` to be called once the request is finished.
  407. ///
  408. /// - Parameters:
  409. /// - queue: The queue on which the completion handler is called. `.main` by default.
  410. /// - completionHandler: A closure to be executed once the request has finished.
  411. ///
  412. /// - Returns: The request.
  413. @preconcurrency
  414. @discardableResult
  415. public func responseURL(queue: DispatchQueue = .main,
  416. completionHandler: @Sendable @escaping (AFDownloadResponse<URL>) -> Void) -> Self {
  417. response(queue: queue, responseSerializer: URLResponseSerializer(), completionHandler: completionHandler)
  418. }
  419. /// Adds a handler using a `DataResponseSerializer` to be called once the request has finished.
  420. ///
  421. /// - Note: This handler will read the entire downloaded file into memory, use with caution.
  422. ///
  423. /// - Parameters:
  424. /// - queue: The queue on which the completion handler is called. `.main` by default.
  425. /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before calling the
  426. /// `completionHandler`. `PassthroughPreprocessor()` by default.
  427. /// - emptyResponseCodes: HTTP status codes for which empty responses are always valid. `[204, 205]` by default.
  428. /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default.
  429. /// - completionHandler: A closure to be executed once the request has finished.
  430. ///
  431. /// - Returns: The request.
  432. @preconcurrency
  433. @discardableResult
  434. public func responseData(queue: DispatchQueue = .main,
  435. dataPreprocessor: any DataPreprocessor = DataResponseSerializer.defaultDataPreprocessor,
  436. emptyResponseCodes: Set<Int> = DataResponseSerializer.defaultEmptyResponseCodes,
  437. emptyRequestMethods: Set<HTTPMethod> = DataResponseSerializer.defaultEmptyRequestMethods,
  438. completionHandler: @Sendable @escaping (AFDownloadResponse<Data>) -> Void) -> Self {
  439. response(queue: queue,
  440. responseSerializer: DataResponseSerializer(dataPreprocessor: dataPreprocessor,
  441. emptyResponseCodes: emptyResponseCodes,
  442. emptyRequestMethods: emptyRequestMethods),
  443. completionHandler: completionHandler)
  444. }
  445. /// Adds a handler using a `StringResponseSerializer` to be called once the request has finished.
  446. ///
  447. /// - Note: This handler will read the entire downloaded file into memory, use with caution.
  448. ///
  449. /// - Parameters:
  450. /// - queue: The queue on which the completion handler is dispatched. `.main` by default.
  451. /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before calling the
  452. /// `completionHandler`. `PassthroughPreprocessor()` by default.
  453. /// - encoding: The string encoding. Defaults to `nil`, in which case the encoding will be determined
  454. /// from the server response, falling back to the default HTTP character set, `ISO-8859-1`.
  455. /// - emptyResponseCodes: HTTP status codes for which empty responses are always valid. `[204, 205]` by default.
  456. /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default.
  457. /// - completionHandler: A closure to be executed once the request has finished.
  458. ///
  459. /// - Returns: The request.
  460. @preconcurrency
  461. @discardableResult
  462. public func responseString(queue: DispatchQueue = .main,
  463. dataPreprocessor: any DataPreprocessor = StringResponseSerializer.defaultDataPreprocessor,
  464. encoding: String.Encoding? = nil,
  465. emptyResponseCodes: Set<Int> = StringResponseSerializer.defaultEmptyResponseCodes,
  466. emptyRequestMethods: Set<HTTPMethod> = StringResponseSerializer.defaultEmptyRequestMethods,
  467. completionHandler: @Sendable @escaping (AFDownloadResponse<String>) -> Void) -> Self {
  468. response(queue: queue,
  469. responseSerializer: StringResponseSerializer(dataPreprocessor: dataPreprocessor,
  470. encoding: encoding,
  471. emptyResponseCodes: emptyResponseCodes,
  472. emptyRequestMethods: emptyRequestMethods),
  473. completionHandler: completionHandler)
  474. }
  475. /// Adds a handler using a `JSONResponseSerializer` to be called once the request has finished.
  476. ///
  477. /// - Note: This handler will read the entire downloaded file into memory, use with caution.
  478. ///
  479. /// - Parameters:
  480. /// - queue: The queue on which the completion handler is dispatched. `.main` by default.
  481. /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before calling the
  482. /// `completionHandler`. `PassthroughPreprocessor()` by default.
  483. /// - emptyResponseCodes: HTTP status codes for which empty responses are always valid. `[204, 205]` by default.
  484. /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default.
  485. /// - options: `JSONSerialization.ReadingOptions` used when parsing the response. `.allowFragments`
  486. /// by default.
  487. /// - completionHandler: A closure to be executed once the request has finished.
  488. ///
  489. /// - Returns: The request.
  490. @available(*, deprecated, message: "responseJSON deprecated and will be removed in Alamofire 6. Use responseDecodable instead.")
  491. @preconcurrency
  492. @discardableResult
  493. public func responseJSON(queue: DispatchQueue = .main,
  494. dataPreprocessor: any DataPreprocessor = JSONResponseSerializer.defaultDataPreprocessor,
  495. emptyResponseCodes: Set<Int> = JSONResponseSerializer.defaultEmptyResponseCodes,
  496. emptyRequestMethods: Set<HTTPMethod> = JSONResponseSerializer.defaultEmptyRequestMethods,
  497. options: JSONSerialization.ReadingOptions = .allowFragments,
  498. completionHandler: @Sendable @escaping (AFDownloadResponse<any Any & Sendable>) -> Void) -> Self {
  499. response(queue: queue,
  500. responseSerializer: JSONResponseSerializer(dataPreprocessor: dataPreprocessor,
  501. emptyResponseCodes: emptyResponseCodes,
  502. emptyRequestMethods: emptyRequestMethods,
  503. options: options),
  504. completionHandler: completionHandler)
  505. }
  506. /// Adds a handler using a `DecodableResponseSerializer` to be called once the request has finished.
  507. ///
  508. /// - Note: This handler will read the entire downloaded file into memory, use with caution.
  509. ///
  510. /// - Parameters:
  511. /// - type: `Decodable` type to decode from response data.
  512. /// - queue: The queue on which the completion handler is dispatched. `.main` by default.
  513. /// - dataPreprocessor: `DataPreprocessor` which processes the received `Data` before calling the
  514. /// `completionHandler`. `PassthroughPreprocessor()` by default.
  515. /// - decoder: `DataDecoder` to use to decode the response. `JSONDecoder()` by default.
  516. /// - emptyResponseCodes: HTTP status codes for which empty responses are always valid. `[204, 205]` by default.
  517. /// - emptyRequestMethods: `HTTPMethod`s for which empty responses are always valid. `[.head]` by default.
  518. /// - completionHandler: A closure to be executed once the request has finished.
  519. ///
  520. /// - Returns: The request.
  521. @preconcurrency
  522. @discardableResult
  523. public func responseDecodable<T: Decodable>(of type: T.Type = T.self,
  524. queue: DispatchQueue = .main,
  525. dataPreprocessor: any DataPreprocessor = DecodableResponseSerializer<T>.defaultDataPreprocessor,
  526. decoder: any DataDecoder = JSONDecoder(),
  527. emptyResponseCodes: Set<Int> = DecodableResponseSerializer<T>.defaultEmptyResponseCodes,
  528. emptyRequestMethods: Set<HTTPMethod> = DecodableResponseSerializer<T>.defaultEmptyRequestMethods,
  529. completionHandler: @Sendable @escaping (AFDownloadResponse<T>) -> Void) -> Self where T: Sendable {
  530. response(queue: queue,
  531. responseSerializer: DecodableResponseSerializer(dataPreprocessor: dataPreprocessor,
  532. decoder: decoder,
  533. emptyResponseCodes: emptyResponseCodes,
  534. emptyRequestMethods: emptyRequestMethods),
  535. completionHandler: completionHandler)
  536. }
  537. }