Request.swift 84 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070
  1. //
  2. // Request.swift
  3. //
  4. // Copyright (c) 2014-2020 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` is the common superclass of all Alamofire request types and provides common state, delegate, and callback
  26. /// handling.
  27. public class Request {
  28. /// State of the `Request`, with managed transitions between states set when calling `resume()`, `suspend()`, or
  29. /// `cancel()` on the `Request`.
  30. public enum State {
  31. /// Initial state of the `Request`.
  32. case initialized
  33. /// `State` set when `resume()` is called. Any tasks created for the `Request` will have `resume()` called on
  34. /// them in this state.
  35. case resumed
  36. /// `State` set when `suspend()` is called. Any tasks created for the `Request` will have `suspend()` called on
  37. /// them in this state.
  38. case suspended
  39. /// `State` set when `cancel()` is called. Any tasks created for the `Request` will have `cancel()` called on
  40. /// them. Unlike `resumed` or `suspended`, once in the `cancelled` state, the `Request` can no longer transition
  41. /// to any other state.
  42. case cancelled
  43. /// `State` set when all response serialization completion closures have been cleared on the `Request` and
  44. /// enqueued on their respective queues.
  45. case finished
  46. /// Determines whether `self` can be transitioned to the provided `State`.
  47. func canTransitionTo(_ state: State) -> Bool {
  48. switch (self, state) {
  49. case (.initialized, _):
  50. return true
  51. case (_, .initialized), (.cancelled, _), (.finished, _):
  52. return false
  53. case (.resumed, .cancelled), (.suspended, .cancelled), (.resumed, .suspended), (.suspended, .resumed):
  54. return true
  55. case (.suspended, .suspended), (.resumed, .resumed):
  56. return false
  57. case (_, .finished):
  58. return true
  59. }
  60. }
  61. }
  62. // MARK: - Initial State
  63. /// `UUID` providing a unique identifier for the `Request`, used in the `Hashable` and `Equatable` conformances.
  64. public let id: UUID
  65. /// The serial queue for all internal async actions.
  66. public let underlyingQueue: DispatchQueue
  67. /// The queue used for all serialization actions. By default it's a serial queue that targets `underlyingQueue`.
  68. public let serializationQueue: DispatchQueue
  69. /// `EventMonitor` used for event callbacks.
  70. public let eventMonitor: EventMonitor?
  71. /// The `Request`'s interceptor.
  72. public let interceptor: RequestInterceptor?
  73. /// The `Request`'s delegate.
  74. public private(set) weak var delegate: RequestDelegate?
  75. // MARK: - Mutable State
  76. /// Type encapsulating all mutable state that may need to be accessed from anything other than the `underlyingQueue`.
  77. struct MutableState {
  78. /// State of the `Request`.
  79. var state: State = .initialized
  80. /// `ProgressHandler` and `DispatchQueue` provided for upload progress callbacks.
  81. var uploadProgressHandler: (handler: ProgressHandler, queue: DispatchQueue)?
  82. /// `ProgressHandler` and `DispatchQueue` provided for download progress callbacks.
  83. var downloadProgressHandler: (handler: ProgressHandler, queue: DispatchQueue)?
  84. /// `RedirectHandler` provided for to handle request redirection.
  85. var redirectHandler: RedirectHandler?
  86. /// `CachedResponseHandler` provided to handle response caching.
  87. var cachedResponseHandler: CachedResponseHandler?
  88. /// Queue and closure called when the `Request` is able to create a cURL description of itself.
  89. var cURLHandler: (queue: DispatchQueue, handler: (String) -> Void)?
  90. /// Queue and closure called when the `Request` creates a `URLRequest`.
  91. var urlRequestHandler: (queue: DispatchQueue, handler: (URLRequest) -> Void)?
  92. /// Queue and closure called when the `Request` creates a `URLSessionTask`.
  93. var urlSessionTaskHandler: (queue: DispatchQueue, handler: (URLSessionTask) -> Void)?
  94. /// Response serialization closures that handle response parsing.
  95. var responseSerializers: [() -> Void] = []
  96. /// Response serialization completion closures executed once all response serializers are complete.
  97. var responseSerializerCompletions: [() -> Void] = []
  98. /// Whether response serializer processing is finished.
  99. var responseSerializerProcessingFinished = false
  100. /// `URLCredential` used for authentication challenges.
  101. var credential: URLCredential?
  102. /// All `URLRequest`s created by Alamofire on behalf of the `Request`.
  103. var requests: [URLRequest] = []
  104. /// All `URLSessionTask`s created by Alamofire on behalf of the `Request`.
  105. var tasks: [URLSessionTask] = []
  106. /// All `URLSessionTaskMetrics` values gathered by Alamofire on behalf of the `Request`. Should correspond
  107. /// exactly the the `tasks` created.
  108. var metrics: [URLSessionTaskMetrics] = []
  109. /// Number of times any retriers provided retried the `Request`.
  110. var retryCount = 0
  111. /// Final `AFError` for the `Request`, whether from various internal Alamofire calls or as a result of a `task`.
  112. var error: AFError?
  113. /// Whether the instance has had `finish()` called and is running the serializers. Should be replaced with a
  114. /// representation in the state machine in the future.
  115. var isFinishing = false
  116. /// Actions to run when requests are finished. Use for concurrency support.
  117. var finishHandlers: [() -> Void] = []
  118. }
  119. /// Protected `MutableState` value that provides thread-safe access to state values.
  120. @Protected
  121. fileprivate var mutableState = MutableState()
  122. /// `State` of the `Request`.
  123. public var state: State { $mutableState.state }
  124. /// Returns whether `state` is `.initialized`.
  125. public var isInitialized: Bool { state == .initialized }
  126. /// Returns whether `state is `.resumed`.
  127. public var isResumed: Bool { state == .resumed }
  128. /// Returns whether `state` is `.suspended`.
  129. public var isSuspended: Bool { state == .suspended }
  130. /// Returns whether `state` is `.cancelled`.
  131. public var isCancelled: Bool { state == .cancelled }
  132. /// Returns whether `state` is `.finished`.
  133. public var isFinished: Bool { state == .finished }
  134. // MARK: Progress
  135. /// Closure type executed when monitoring the upload or download progress of a request.
  136. public typealias ProgressHandler = (Progress) -> Void
  137. /// `Progress` of the upload of the body of the executed `URLRequest`. Reset to `0` if the `Request` is retried.
  138. public let uploadProgress = Progress(totalUnitCount: 0)
  139. /// `Progress` of the download of any response data. Reset to `0` if the `Request` is retried.
  140. public let downloadProgress = Progress(totalUnitCount: 0)
  141. /// `ProgressHandler` called when `uploadProgress` is updated, on the provided `DispatchQueue`.
  142. private var uploadProgressHandler: (handler: ProgressHandler, queue: DispatchQueue)? {
  143. get { $mutableState.uploadProgressHandler }
  144. set { $mutableState.uploadProgressHandler = newValue }
  145. }
  146. /// `ProgressHandler` called when `downloadProgress` is updated, on the provided `DispatchQueue`.
  147. fileprivate var downloadProgressHandler: (handler: ProgressHandler, queue: DispatchQueue)? {
  148. get { $mutableState.downloadProgressHandler }
  149. set { $mutableState.downloadProgressHandler = newValue }
  150. }
  151. // MARK: Redirect Handling
  152. /// `RedirectHandler` set on the instance.
  153. public private(set) var redirectHandler: RedirectHandler? {
  154. get { $mutableState.redirectHandler }
  155. set { $mutableState.redirectHandler = newValue }
  156. }
  157. // MARK: Cached Response Handling
  158. /// `CachedResponseHandler` set on the instance.
  159. public private(set) var cachedResponseHandler: CachedResponseHandler? {
  160. get { $mutableState.cachedResponseHandler }
  161. set { $mutableState.cachedResponseHandler = newValue }
  162. }
  163. // MARK: URLCredential
  164. /// `URLCredential` used for authentication challenges. Created by calling one of the `authenticate` methods.
  165. public private(set) var credential: URLCredential? {
  166. get { $mutableState.credential }
  167. set { $mutableState.credential = newValue }
  168. }
  169. // MARK: Validators
  170. /// `Validator` callback closures that store the validation calls enqueued.
  171. @Protected
  172. fileprivate var validators: [() -> Void] = []
  173. // MARK: URLRequests
  174. /// All `URLRequests` created on behalf of the `Request`, including original and adapted requests.
  175. public var requests: [URLRequest] { $mutableState.requests }
  176. /// First `URLRequest` created on behalf of the `Request`. May not be the first one actually executed.
  177. public var firstRequest: URLRequest? { requests.first }
  178. /// Last `URLRequest` created on behalf of the `Request`.
  179. public var lastRequest: URLRequest? { requests.last }
  180. /// Current `URLRequest` created on behalf of the `Request`.
  181. public var request: URLRequest? { lastRequest }
  182. /// `URLRequest`s from all of the `URLSessionTask`s executed on behalf of the `Request`. May be different from
  183. /// `requests` due to `URLSession` manipulation.
  184. public var performedRequests: [URLRequest] { $mutableState.read { $0.tasks.compactMap(\.currentRequest) } }
  185. // MARK: HTTPURLResponse
  186. /// `HTTPURLResponse` received from the server, if any. If the `Request` was retried, this is the response of the
  187. /// last `URLSessionTask`.
  188. public var response: HTTPURLResponse? { lastTask?.response as? HTTPURLResponse }
  189. // MARK: Tasks
  190. /// All `URLSessionTask`s created on behalf of the `Request`.
  191. public var tasks: [URLSessionTask] { $mutableState.tasks }
  192. /// First `URLSessionTask` created on behalf of the `Request`.
  193. public var firstTask: URLSessionTask? { tasks.first }
  194. /// Last `URLSessionTask` created on behalf of the `Request`.
  195. public var lastTask: URLSessionTask? { tasks.last }
  196. /// Current `URLSessionTask` created on behalf of the `Request`.
  197. public var task: URLSessionTask? { lastTask }
  198. // MARK: Metrics
  199. /// All `URLSessionTaskMetrics` gathered on behalf of the `Request`. Should correspond to the `tasks` created.
  200. public var allMetrics: [URLSessionTaskMetrics] { $mutableState.metrics }
  201. /// First `URLSessionTaskMetrics` gathered on behalf of the `Request`.
  202. public var firstMetrics: URLSessionTaskMetrics? { allMetrics.first }
  203. /// Last `URLSessionTaskMetrics` gathered on behalf of the `Request`.
  204. public var lastMetrics: URLSessionTaskMetrics? { allMetrics.last }
  205. /// Current `URLSessionTaskMetrics` gathered on behalf of the `Request`.
  206. public var metrics: URLSessionTaskMetrics? { lastMetrics }
  207. // MARK: Retry Count
  208. /// Number of times the `Request` has been retried.
  209. public var retryCount: Int { $mutableState.retryCount }
  210. // MARK: Error
  211. /// `Error` returned from Alamofire internally, from the network request directly, or any validators executed.
  212. public fileprivate(set) var error: AFError? {
  213. get { $mutableState.error }
  214. set { $mutableState.error = newValue }
  215. }
  216. /// Default initializer for the `Request` superclass.
  217. ///
  218. /// - Parameters:
  219. /// - id: `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()` by default.
  220. /// - underlyingQueue: `DispatchQueue` on which all internal `Request` work is performed.
  221. /// - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default targets
  222. /// `underlyingQueue`, but can be passed another queue from a `Session`.
  223. /// - eventMonitor: `EventMonitor` called for event callbacks from internal `Request` actions.
  224. /// - interceptor: `RequestInterceptor` used throughout the request lifecycle.
  225. /// - delegate: `RequestDelegate` that provides an interface to actions not performed by the `Request`.
  226. init(id: UUID = UUID(),
  227. underlyingQueue: DispatchQueue,
  228. serializationQueue: DispatchQueue,
  229. eventMonitor: EventMonitor?,
  230. interceptor: RequestInterceptor?,
  231. delegate: RequestDelegate) {
  232. self.id = id
  233. self.underlyingQueue = underlyingQueue
  234. self.serializationQueue = serializationQueue
  235. self.eventMonitor = eventMonitor
  236. self.interceptor = interceptor
  237. self.delegate = delegate
  238. }
  239. // MARK: - Internal Event API
  240. // All API must be called from underlyingQueue.
  241. /// Called when an initial `URLRequest` has been created on behalf of the instance. If a `RequestAdapter` is active,
  242. /// the `URLRequest` will be adapted before being issued.
  243. ///
  244. /// - Parameter request: The `URLRequest` created.
  245. func didCreateInitialURLRequest(_ request: URLRequest) {
  246. dispatchPrecondition(condition: .onQueue(underlyingQueue))
  247. $mutableState.write { $0.requests.append(request) }
  248. eventMonitor?.request(self, didCreateInitialURLRequest: request)
  249. }
  250. /// Called when initial `URLRequest` creation has failed, typically through a `URLRequestConvertible`.
  251. ///
  252. /// - Note: Triggers retry.
  253. ///
  254. /// - Parameter error: `AFError` thrown from the failed creation.
  255. func didFailToCreateURLRequest(with error: AFError) {
  256. dispatchPrecondition(condition: .onQueue(underlyingQueue))
  257. self.error = error
  258. eventMonitor?.request(self, didFailToCreateURLRequestWithError: error)
  259. callCURLHandlerIfNecessary()
  260. retryOrFinish(error: error)
  261. }
  262. /// Called when a `RequestAdapter` has successfully adapted a `URLRequest`.
  263. ///
  264. /// - Parameters:
  265. /// - initialRequest: The `URLRequest` that was adapted.
  266. /// - adaptedRequest: The `URLRequest` returned by the `RequestAdapter`.
  267. func didAdaptInitialRequest(_ initialRequest: URLRequest, to adaptedRequest: URLRequest) {
  268. dispatchPrecondition(condition: .onQueue(underlyingQueue))
  269. $mutableState.write { $0.requests.append(adaptedRequest) }
  270. eventMonitor?.request(self, didAdaptInitialRequest: initialRequest, to: adaptedRequest)
  271. }
  272. /// Called when a `RequestAdapter` fails to adapt a `URLRequest`.
  273. ///
  274. /// - Note: Triggers retry.
  275. ///
  276. /// - Parameters:
  277. /// - request: The `URLRequest` the adapter was called with.
  278. /// - error: The `AFError` returned by the `RequestAdapter`.
  279. func didFailToAdaptURLRequest(_ request: URLRequest, withError error: AFError) {
  280. dispatchPrecondition(condition: .onQueue(underlyingQueue))
  281. self.error = error
  282. eventMonitor?.request(self, didFailToAdaptURLRequest: request, withError: error)
  283. callCURLHandlerIfNecessary()
  284. retryOrFinish(error: error)
  285. }
  286. /// Final `URLRequest` has been created for the instance.
  287. ///
  288. /// - Parameter request: The `URLRequest` created.
  289. func didCreateURLRequest(_ request: URLRequest) {
  290. dispatchPrecondition(condition: .onQueue(underlyingQueue))
  291. $mutableState.read { state in
  292. state.urlRequestHandler?.queue.async { state.urlRequestHandler?.handler(request) }
  293. }
  294. eventMonitor?.request(self, didCreateURLRequest: request)
  295. callCURLHandlerIfNecessary()
  296. }
  297. /// Asynchronously calls any stored `cURLHandler` and then removes it from `mutableState`.
  298. private func callCURLHandlerIfNecessary() {
  299. $mutableState.write { mutableState in
  300. guard let cURLHandler = mutableState.cURLHandler else { return }
  301. cURLHandler.queue.async { cURLHandler.handler(self.cURLDescription()) }
  302. mutableState.cURLHandler = nil
  303. }
  304. }
  305. /// Called when a `URLSessionTask` is created on behalf of the instance.
  306. ///
  307. /// - Parameter task: The `URLSessionTask` created.
  308. func didCreateTask(_ task: URLSessionTask) {
  309. dispatchPrecondition(condition: .onQueue(underlyingQueue))
  310. $mutableState.write { state in
  311. state.tasks.append(task)
  312. guard let urlSessionTaskHandler = state.urlSessionTaskHandler else { return }
  313. urlSessionTaskHandler.queue.async { urlSessionTaskHandler.handler(task) }
  314. }
  315. eventMonitor?.request(self, didCreateTask: task)
  316. }
  317. /// Called when resumption is completed.
  318. func didResume() {
  319. dispatchPrecondition(condition: .onQueue(underlyingQueue))
  320. eventMonitor?.requestDidResume(self)
  321. }
  322. /// Called when a `URLSessionTask` is resumed on behalf of the instance.
  323. ///
  324. /// - Parameter task: The `URLSessionTask` resumed.
  325. func didResumeTask(_ task: URLSessionTask) {
  326. dispatchPrecondition(condition: .onQueue(underlyingQueue))
  327. eventMonitor?.request(self, didResumeTask: task)
  328. }
  329. /// Called when suspension is completed.
  330. func didSuspend() {
  331. dispatchPrecondition(condition: .onQueue(underlyingQueue))
  332. eventMonitor?.requestDidSuspend(self)
  333. }
  334. /// Called when a `URLSessionTask` is suspended on behalf of the instance.
  335. ///
  336. /// - Parameter task: The `URLSessionTask` suspended.
  337. func didSuspendTask(_ task: URLSessionTask) {
  338. dispatchPrecondition(condition: .onQueue(underlyingQueue))
  339. eventMonitor?.request(self, didSuspendTask: task)
  340. }
  341. /// Called when cancellation is completed, sets `error` to `AFError.explicitlyCancelled`.
  342. func didCancel() {
  343. dispatchPrecondition(condition: .onQueue(underlyingQueue))
  344. $mutableState.write { mutableState in
  345. mutableState.error = mutableState.error ?? AFError.explicitlyCancelled
  346. }
  347. eventMonitor?.requestDidCancel(self)
  348. }
  349. /// Called when a `URLSessionTask` is cancelled on behalf of the instance.
  350. ///
  351. /// - Parameter task: The `URLSessionTask` cancelled.
  352. func didCancelTask(_ task: URLSessionTask) {
  353. dispatchPrecondition(condition: .onQueue(underlyingQueue))
  354. eventMonitor?.request(self, didCancelTask: task)
  355. }
  356. /// Called when a `URLSessionTaskMetrics` value is gathered on behalf of the instance.
  357. ///
  358. /// - Parameter metrics: The `URLSessionTaskMetrics` gathered.
  359. func didGatherMetrics(_ metrics: URLSessionTaskMetrics) {
  360. dispatchPrecondition(condition: .onQueue(underlyingQueue))
  361. $mutableState.write { $0.metrics.append(metrics) }
  362. eventMonitor?.request(self, didGatherMetrics: metrics)
  363. }
  364. /// Called when a `URLSessionTask` fails before it is finished, typically during certificate pinning.
  365. ///
  366. /// - Parameters:
  367. /// - task: The `URLSessionTask` which failed.
  368. /// - error: The early failure `AFError`.
  369. func didFailTask(_ task: URLSessionTask, earlyWithError error: AFError) {
  370. dispatchPrecondition(condition: .onQueue(underlyingQueue))
  371. self.error = error
  372. // Task will still complete, so didCompleteTask(_:with:) will handle retry.
  373. eventMonitor?.request(self, didFailTask: task, earlyWithError: error)
  374. }
  375. /// Called when a `URLSessionTask` completes. All tasks will eventually call this method.
  376. ///
  377. /// - Note: Response validation is synchronously triggered in this step.
  378. ///
  379. /// - Parameters:
  380. /// - task: The `URLSessionTask` which completed.
  381. /// - error: The `AFError` `task` may have completed with. If `error` has already been set on the instance, this
  382. /// value is ignored.
  383. func didCompleteTask(_ task: URLSessionTask, with error: AFError?) {
  384. dispatchPrecondition(condition: .onQueue(underlyingQueue))
  385. self.error = self.error ?? error
  386. validators.forEach { $0() }
  387. eventMonitor?.request(self, didCompleteTask: task, with: error)
  388. retryOrFinish(error: self.error)
  389. }
  390. /// Called when the `RequestDelegate` is going to retry this `Request`. Calls `reset()`.
  391. func prepareForRetry() {
  392. dispatchPrecondition(condition: .onQueue(underlyingQueue))
  393. $mutableState.write { $0.retryCount += 1 }
  394. reset()
  395. eventMonitor?.requestIsRetrying(self)
  396. }
  397. /// Called to determine whether retry will be triggered for the particular error, or whether the instance should
  398. /// call `finish()`.
  399. ///
  400. /// - Parameter error: The possible `AFError` which may trigger retry.
  401. func retryOrFinish(error: AFError?) {
  402. dispatchPrecondition(condition: .onQueue(underlyingQueue))
  403. guard !isCancelled, let error = error, let delegate = delegate else { finish(); return }
  404. delegate.retryResult(for: self, dueTo: error) { retryResult in
  405. switch retryResult {
  406. case .doNotRetry:
  407. self.finish()
  408. case let .doNotRetryWithError(retryError):
  409. self.finish(error: retryError.asAFError(orFailWith: "Received retryError was not already AFError"))
  410. case .retry, .retryWithDelay:
  411. delegate.retryRequest(self, withDelay: retryResult.delay)
  412. }
  413. }
  414. }
  415. /// Finishes this `Request` and starts the response serializers.
  416. ///
  417. /// - Parameter error: The possible `Error` with which the instance will finish.
  418. func finish(error: AFError? = nil) {
  419. dispatchPrecondition(condition: .onQueue(underlyingQueue))
  420. guard !$mutableState.isFinishing else { return }
  421. $mutableState.isFinishing = true
  422. if let error = error { self.error = error }
  423. // Start response handlers
  424. processNextResponseSerializer()
  425. eventMonitor?.requestDidFinish(self)
  426. }
  427. /// Appends the response serialization closure to the instance.
  428. ///
  429. /// - Note: This method will also `resume` the instance if `delegate.startImmediately` returns `true`.
  430. ///
  431. /// - Parameter closure: The closure containing the response serialization call.
  432. func appendResponseSerializer(_ closure: @escaping () -> Void) {
  433. $mutableState.write { mutableState in
  434. mutableState.responseSerializers.append(closure)
  435. if mutableState.state == .finished {
  436. mutableState.state = .resumed
  437. }
  438. if mutableState.responseSerializerProcessingFinished {
  439. underlyingQueue.async { self.processNextResponseSerializer() }
  440. }
  441. if mutableState.state.canTransitionTo(.resumed) {
  442. underlyingQueue.async { if self.delegate?.startImmediately == true { self.resume() } }
  443. }
  444. }
  445. }
  446. /// Returns the next response serializer closure to execute if there's one left.
  447. ///
  448. /// - Returns: The next response serialization closure, if there is one.
  449. func nextResponseSerializer() -> (() -> Void)? {
  450. var responseSerializer: (() -> Void)?
  451. $mutableState.write { mutableState in
  452. let responseSerializerIndex = mutableState.responseSerializerCompletions.count
  453. if responseSerializerIndex < mutableState.responseSerializers.count {
  454. responseSerializer = mutableState.responseSerializers[responseSerializerIndex]
  455. }
  456. }
  457. return responseSerializer
  458. }
  459. /// Processes the next response serializer and calls all completions if response serialization is complete.
  460. func processNextResponseSerializer() {
  461. guard let responseSerializer = nextResponseSerializer() else {
  462. // Execute all response serializer completions and clear them
  463. var completions: [() -> Void] = []
  464. $mutableState.write { mutableState in
  465. completions = mutableState.responseSerializerCompletions
  466. // Clear out all response serializers and response serializer completions in mutable state since the
  467. // request is complete. It's important to do this prior to calling the completion closures in case
  468. // the completions call back into the request triggering a re-processing of the response serializers.
  469. // An example of how this can happen is by calling cancel inside a response completion closure.
  470. mutableState.responseSerializers.removeAll()
  471. mutableState.responseSerializerCompletions.removeAll()
  472. if mutableState.state.canTransitionTo(.finished) {
  473. mutableState.state = .finished
  474. }
  475. mutableState.responseSerializerProcessingFinished = true
  476. mutableState.isFinishing = false
  477. }
  478. completions.forEach { $0() }
  479. // Cleanup the request
  480. cleanup()
  481. return
  482. }
  483. serializationQueue.async { responseSerializer() }
  484. }
  485. /// Notifies the `Request` that the response serializer is complete.
  486. ///
  487. /// - Parameter completion: The completion handler provided with the response serializer, called when all serializers
  488. /// are complete.
  489. func responseSerializerDidComplete(completion: @escaping () -> Void) {
  490. $mutableState.write { $0.responseSerializerCompletions.append(completion) }
  491. processNextResponseSerializer()
  492. }
  493. /// Resets all task and response serializer related state for retry.
  494. func reset() {
  495. error = nil
  496. uploadProgress.totalUnitCount = 0
  497. uploadProgress.completedUnitCount = 0
  498. downloadProgress.totalUnitCount = 0
  499. downloadProgress.completedUnitCount = 0
  500. $mutableState.write { state in
  501. state.isFinishing = false
  502. state.responseSerializerCompletions = []
  503. }
  504. }
  505. /// Called when updating the upload progress.
  506. ///
  507. /// - Parameters:
  508. /// - totalBytesSent: Total bytes sent so far.
  509. /// - totalBytesExpectedToSend: Total bytes expected to send.
  510. func updateUploadProgress(totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
  511. uploadProgress.totalUnitCount = totalBytesExpectedToSend
  512. uploadProgress.completedUnitCount = totalBytesSent
  513. uploadProgressHandler?.queue.async { self.uploadProgressHandler?.handler(self.uploadProgress) }
  514. }
  515. /// Perform a closure on the current `state` while locked.
  516. ///
  517. /// - Parameter perform: The closure to perform.
  518. func withState(perform: (State) -> Void) {
  519. $mutableState.withState(perform: perform)
  520. }
  521. // MARK: Task Creation
  522. /// Called when creating a `URLSessionTask` for this `Request`. Subclasses must override.
  523. ///
  524. /// - Parameters:
  525. /// - request: `URLRequest` to use to create the `URLSessionTask`.
  526. /// - session: `URLSession` which creates the `URLSessionTask`.
  527. ///
  528. /// - Returns: The `URLSessionTask` created.
  529. func task(for request: URLRequest, using session: URLSession) -> URLSessionTask {
  530. fatalError("Subclasses must override.")
  531. }
  532. // MARK: - Public API
  533. // These APIs are callable from any queue.
  534. // MARK: State
  535. /// Cancels the instance. Once cancelled, a `Request` can no longer be resumed or suspended.
  536. ///
  537. /// - Returns: The instance.
  538. @discardableResult
  539. public func cancel() -> Self {
  540. $mutableState.write { mutableState in
  541. guard mutableState.state.canTransitionTo(.cancelled) else { return }
  542. mutableState.state = .cancelled
  543. underlyingQueue.async { self.didCancel() }
  544. guard let task = mutableState.tasks.last, task.state != .completed else {
  545. underlyingQueue.async { self.finish() }
  546. return
  547. }
  548. // Resume to ensure metrics are gathered.
  549. task.resume()
  550. task.cancel()
  551. underlyingQueue.async { self.didCancelTask(task) }
  552. }
  553. return self
  554. }
  555. /// Suspends the instance.
  556. ///
  557. /// - Returns: The instance.
  558. @discardableResult
  559. public func suspend() -> Self {
  560. $mutableState.write { mutableState in
  561. guard mutableState.state.canTransitionTo(.suspended) else { return }
  562. mutableState.state = .suspended
  563. underlyingQueue.async { self.didSuspend() }
  564. guard let task = mutableState.tasks.last, task.state != .completed else { return }
  565. task.suspend()
  566. underlyingQueue.async { self.didSuspendTask(task) }
  567. }
  568. return self
  569. }
  570. /// Resumes the instance.
  571. ///
  572. /// - Returns: The instance.
  573. @discardableResult
  574. public func resume() -> Self {
  575. $mutableState.write { mutableState in
  576. guard mutableState.state.canTransitionTo(.resumed) else { return }
  577. mutableState.state = .resumed
  578. underlyingQueue.async { self.didResume() }
  579. guard let task = mutableState.tasks.last, task.state != .completed else { return }
  580. task.resume()
  581. underlyingQueue.async { self.didResumeTask(task) }
  582. }
  583. return self
  584. }
  585. // MARK: - Closure API
  586. /// Associates a credential using the provided values with the instance.
  587. ///
  588. /// - Parameters:
  589. /// - username: The username.
  590. /// - password: The password.
  591. /// - persistence: The `URLCredential.Persistence` for the created `URLCredential`. `.forSession` by default.
  592. ///
  593. /// - Returns: The instance.
  594. @discardableResult
  595. public func authenticate(username: String, password: String, persistence: URLCredential.Persistence = .forSession) -> Self {
  596. let credential = URLCredential(user: username, password: password, persistence: persistence)
  597. return authenticate(with: credential)
  598. }
  599. /// Associates the provided credential with the instance.
  600. ///
  601. /// - Parameter credential: The `URLCredential`.
  602. ///
  603. /// - Returns: The instance.
  604. @discardableResult
  605. public func authenticate(with credential: URLCredential) -> Self {
  606. $mutableState.credential = credential
  607. return self
  608. }
  609. /// Sets a closure to be called periodically during the lifecycle of the instance as data is read from the server.
  610. ///
  611. /// - Note: Only the last closure provided is used.
  612. ///
  613. /// - Parameters:
  614. /// - queue: The `DispatchQueue` to execute the closure on. `.main` by default.
  615. /// - closure: The closure to be executed periodically as data is read from the server.
  616. ///
  617. /// - Returns: The instance.
  618. @discardableResult
  619. public func downloadProgress(queue: DispatchQueue = .main, closure: @escaping ProgressHandler) -> Self {
  620. $mutableState.downloadProgressHandler = (handler: closure, queue: queue)
  621. return self
  622. }
  623. /// Sets a closure to be called periodically during the lifecycle of the instance as data is sent to the server.
  624. ///
  625. /// - Note: Only the last closure provided is used.
  626. ///
  627. /// - Parameters:
  628. /// - queue: The `DispatchQueue` to execute the closure on. `.main` by default.
  629. /// - closure: The closure to be executed periodically as data is sent to the server.
  630. ///
  631. /// - Returns: The instance.
  632. @discardableResult
  633. public func uploadProgress(queue: DispatchQueue = .main, closure: @escaping ProgressHandler) -> Self {
  634. $mutableState.uploadProgressHandler = (handler: closure, queue: queue)
  635. return self
  636. }
  637. // MARK: Redirects
  638. /// Sets the redirect handler for the instance which will be used if a redirect response is encountered.
  639. ///
  640. /// - Note: Attempting to set the redirect handler more than once is a logic error and will crash.
  641. ///
  642. /// - Parameter handler: The `RedirectHandler`.
  643. ///
  644. /// - Returns: The instance.
  645. @discardableResult
  646. public func redirect(using handler: RedirectHandler) -> Self {
  647. $mutableState.write { mutableState in
  648. precondition(mutableState.redirectHandler == nil, "Redirect handler has already been set.")
  649. mutableState.redirectHandler = handler
  650. }
  651. return self
  652. }
  653. // MARK: Cached Responses
  654. /// Sets the cached response handler for the `Request` which will be used when attempting to cache a response.
  655. ///
  656. /// - Note: Attempting to set the cache handler more than once is a logic error and will crash.
  657. ///
  658. /// - Parameter handler: The `CachedResponseHandler`.
  659. ///
  660. /// - Returns: The instance.
  661. @discardableResult
  662. public func cacheResponse(using handler: CachedResponseHandler) -> Self {
  663. $mutableState.write { mutableState in
  664. precondition(mutableState.cachedResponseHandler == nil, "Cached response handler has already been set.")
  665. mutableState.cachedResponseHandler = handler
  666. }
  667. return self
  668. }
  669. // MARK: - Lifetime APIs
  670. /// Sets a handler to be called when the cURL description of the request is available.
  671. ///
  672. /// - Note: When waiting for a `Request`'s `URLRequest` to be created, only the last `handler` will be called.
  673. ///
  674. /// - Parameters:
  675. /// - queue: `DispatchQueue` on which `handler` will be called.
  676. /// - handler: Closure to be called when the cURL description is available.
  677. ///
  678. /// - Returns: The instance.
  679. @discardableResult
  680. public func cURLDescription(on queue: DispatchQueue, calling handler: @escaping (String) -> Void) -> Self {
  681. $mutableState.write { mutableState in
  682. if mutableState.requests.last != nil {
  683. queue.async { handler(self.cURLDescription()) }
  684. } else {
  685. mutableState.cURLHandler = (queue, handler)
  686. }
  687. }
  688. return self
  689. }
  690. /// Sets a handler to be called when the cURL description of the request is available.
  691. ///
  692. /// - Note: When waiting for a `Request`'s `URLRequest` to be created, only the last `handler` will be called.
  693. ///
  694. /// - Parameter handler: Closure to be called when the cURL description is available. Called on the instance's
  695. /// `underlyingQueue` by default.
  696. ///
  697. /// - Returns: The instance.
  698. @discardableResult
  699. public func cURLDescription(calling handler: @escaping (String) -> Void) -> Self {
  700. cURLDescription(on: underlyingQueue, calling: handler)
  701. return self
  702. }
  703. /// Sets a closure to called whenever Alamofire creates a `URLRequest` for this instance.
  704. ///
  705. /// - Note: This closure will be called multiple times if the instance adapts incoming `URLRequest`s or is retried.
  706. ///
  707. /// - Parameters:
  708. /// - queue: `DispatchQueue` on which `handler` will be called. `.main` by default.
  709. /// - handler: Closure to be called when a `URLRequest` is available.
  710. ///
  711. /// - Returns: The instance.
  712. @discardableResult
  713. public func onURLRequestCreation(on queue: DispatchQueue = .main, perform handler: @escaping (URLRequest) -> Void) -> Self {
  714. $mutableState.write { state in
  715. if let request = state.requests.last {
  716. queue.async { handler(request) }
  717. }
  718. state.urlRequestHandler = (queue, handler)
  719. }
  720. return self
  721. }
  722. /// Sets a closure to be called whenever the instance creates a `URLSessionTask`.
  723. ///
  724. /// - Note: This API should only be used to provide `URLSessionTask`s to existing API, like `NSFileProvider`. It
  725. /// **SHOULD NOT** be used to interact with tasks directly, as that may be break Alamofire features.
  726. /// Additionally, this closure may be called multiple times if the instance is retried.
  727. ///
  728. /// - Parameters:
  729. /// - queue: `DispatchQueue` on which `handler` will be called. `.main` by default.
  730. /// - handler: Closure to be called when the `URLSessionTask` is available.
  731. ///
  732. /// - Returns: The instance.
  733. @discardableResult
  734. public func onURLSessionTaskCreation(on queue: DispatchQueue = .main, perform handler: @escaping (URLSessionTask) -> Void) -> Self {
  735. $mutableState.write { state in
  736. if let task = state.tasks.last {
  737. queue.async { handler(task) }
  738. }
  739. state.urlSessionTaskHandler = (queue, handler)
  740. }
  741. return self
  742. }
  743. // MARK: Cleanup
  744. /// Adds a `finishHandler` closure to be called when the request completes.
  745. ///
  746. /// - Parameter closure: Closure to be called when the request finishes.
  747. func onFinish(perform finishHandler: @escaping () -> Void) {
  748. guard !isFinished else { finishHandler(); return }
  749. $mutableState.write { state in
  750. state.finishHandlers.append(finishHandler)
  751. }
  752. }
  753. /// Final cleanup step executed when the instance finishes response serialization.
  754. func cleanup() {
  755. let handlers = $mutableState.finishHandlers
  756. handlers.forEach { $0() }
  757. $mutableState.write { state in
  758. state.finishHandlers.removeAll()
  759. }
  760. delegate?.cleanup(after: self)
  761. }
  762. }
  763. extension Request {
  764. /// Type indicating how a `DataRequest` or `DataStreamRequest` should proceed after receiving an `HTTPURLResponse`.
  765. public enum ResponseDisposition {
  766. /// Allow the request to continue normally.
  767. case allow
  768. /// Cancel the request, similar to calling `cancel()`.
  769. case cancel
  770. var sessionDisposition: URLSession.ResponseDisposition {
  771. switch self {
  772. case .allow: return .allow
  773. case .cancel: return .cancel
  774. }
  775. }
  776. }
  777. }
  778. // MARK: - Protocol Conformances
  779. extension Request: Equatable {
  780. public static func ==(lhs: Request, rhs: Request) -> Bool {
  781. lhs.id == rhs.id
  782. }
  783. }
  784. extension Request: Hashable {
  785. public func hash(into hasher: inout Hasher) {
  786. hasher.combine(id)
  787. }
  788. }
  789. extension Request: CustomStringConvertible {
  790. /// A textual representation of this instance, including the `HTTPMethod` and `URL` if the `URLRequest` has been
  791. /// created, as well as the response status code, if a response has been received.
  792. public var description: String {
  793. guard let request = performedRequests.last ?? lastRequest,
  794. let url = request.url,
  795. let method = request.httpMethod else { return "No request created yet." }
  796. let requestDescription = "\(method) \(url.absoluteString)"
  797. return response.map { "\(requestDescription) (\($0.statusCode))" } ?? requestDescription
  798. }
  799. }
  800. extension Request {
  801. /// cURL representation of the instance.
  802. ///
  803. /// - Returns: The cURL equivalent of the instance.
  804. public func cURLDescription() -> String {
  805. guard
  806. let request = lastRequest,
  807. let url = request.url,
  808. let host = url.host,
  809. let method = request.httpMethod else { return "$ curl command could not be created" }
  810. var components = ["$ curl -v"]
  811. components.append("-X \(method)")
  812. if let credentialStorage = delegate?.sessionConfiguration.urlCredentialStorage {
  813. let protectionSpace = URLProtectionSpace(host: host,
  814. port: url.port ?? 0,
  815. protocol: url.scheme,
  816. realm: host,
  817. authenticationMethod: NSURLAuthenticationMethodHTTPBasic)
  818. if let credentials = credentialStorage.credentials(for: protectionSpace)?.values {
  819. for credential in credentials {
  820. guard let user = credential.user, let password = credential.password else { continue }
  821. components.append("-u \(user):\(password)")
  822. }
  823. } else {
  824. if let credential = credential, let user = credential.user, let password = credential.password {
  825. components.append("-u \(user):\(password)")
  826. }
  827. }
  828. }
  829. if let configuration = delegate?.sessionConfiguration, configuration.httpShouldSetCookies {
  830. if
  831. let cookieStorage = configuration.httpCookieStorage,
  832. let cookies = cookieStorage.cookies(for: url), !cookies.isEmpty {
  833. let allCookies = cookies.map { "\($0.name)=\($0.value)" }.joined(separator: ";")
  834. components.append("-b \"\(allCookies)\"")
  835. }
  836. }
  837. var headers = HTTPHeaders()
  838. if let sessionHeaders = delegate?.sessionConfiguration.headers {
  839. for header in sessionHeaders where header.name != "Cookie" {
  840. headers[header.name] = header.value
  841. }
  842. }
  843. for header in request.headers where header.name != "Cookie" {
  844. headers[header.name] = header.value
  845. }
  846. for header in headers {
  847. let escapedValue = header.value.replacingOccurrences(of: "\"", with: "\\\"")
  848. components.append("-H \"\(header.name): \(escapedValue)\"")
  849. }
  850. if let httpBodyData = request.httpBody {
  851. let httpBody = String(decoding: httpBodyData, as: UTF8.self)
  852. var escapedBody = httpBody.replacingOccurrences(of: "\\\"", with: "\\\\\"")
  853. escapedBody = escapedBody.replacingOccurrences(of: "\"", with: "\\\"")
  854. components.append("-d \"\(escapedBody)\"")
  855. }
  856. components.append("\"\(url.absoluteString)\"")
  857. return components.joined(separator: " \\\n\t")
  858. }
  859. }
  860. /// Protocol abstraction for `Request`'s communication back to the `SessionDelegate`.
  861. public protocol RequestDelegate: AnyObject {
  862. /// `URLSessionConfiguration` used to create the underlying `URLSessionTask`s.
  863. var sessionConfiguration: URLSessionConfiguration { get }
  864. /// Determines whether the `Request` should automatically call `resume()` when adding the first response handler.
  865. var startImmediately: Bool { get }
  866. /// Notifies the delegate the `Request` has reached a point where it needs cleanup.
  867. ///
  868. /// - Parameter request: The `Request` to cleanup after.
  869. func cleanup(after request: Request)
  870. /// Asynchronously ask the delegate whether a `Request` will be retried.
  871. ///
  872. /// - Parameters:
  873. /// - request: `Request` which failed.
  874. /// - error: `Error` which produced the failure.
  875. /// - completion: Closure taking the `RetryResult` for evaluation.
  876. func retryResult(for request: Request, dueTo error: AFError, completion: @escaping (RetryResult) -> Void)
  877. /// Asynchronously retry the `Request`.
  878. ///
  879. /// - Parameters:
  880. /// - request: `Request` which will be retried.
  881. /// - timeDelay: `TimeInterval` after which the retry will be triggered.
  882. func retryRequest(_ request: Request, withDelay timeDelay: TimeInterval?)
  883. }
  884. // MARK: - Subclasses
  885. // MARK: - DataRequest
  886. /// `Request` subclass which handles in-memory `Data` download using `URLSessionDataTask`.
  887. public class DataRequest: Request {
  888. /// `URLRequestConvertible` value used to create `URLRequest`s for this instance.
  889. public let convertible: URLRequestConvertible
  890. /// `Data` read from the server so far.
  891. public var data: Data? { $dataMutableState.data }
  892. private struct DataMutableState {
  893. var data: Data?
  894. var httpResponseHandler: (queue: DispatchQueue,
  895. handler: (_ response: HTTPURLResponse,
  896. _ completionHandler: @escaping (ResponseDisposition) -> Void) -> Void)?
  897. }
  898. @Protected
  899. private var dataMutableState = DataMutableState()
  900. /// Creates a `DataRequest` using the provided parameters.
  901. ///
  902. /// - Parameters:
  903. /// - id: `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()` by default.
  904. /// - convertible: `URLRequestConvertible` value used to create `URLRequest`s for this instance.
  905. /// - underlyingQueue: `DispatchQueue` on which all internal `Request` work is performed.
  906. /// - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default targets
  907. /// `underlyingQueue`, but can be passed another queue from a `Session`.
  908. /// - eventMonitor: `EventMonitor` called for event callbacks from internal `Request` actions.
  909. /// - interceptor: `RequestInterceptor` used throughout the request lifecycle.
  910. /// - delegate: `RequestDelegate` that provides an interface to actions not performed by the `Request`.
  911. init(id: UUID = UUID(),
  912. convertible: URLRequestConvertible,
  913. underlyingQueue: DispatchQueue,
  914. serializationQueue: DispatchQueue,
  915. eventMonitor: EventMonitor?,
  916. interceptor: RequestInterceptor?,
  917. delegate: RequestDelegate) {
  918. self.convertible = convertible
  919. super.init(id: id,
  920. underlyingQueue: underlyingQueue,
  921. serializationQueue: serializationQueue,
  922. eventMonitor: eventMonitor,
  923. interceptor: interceptor,
  924. delegate: delegate)
  925. }
  926. override func reset() {
  927. super.reset()
  928. $dataMutableState.write { mutableState in
  929. mutableState.data = nil
  930. }
  931. }
  932. /// Called when `Data` is received by this instance.
  933. ///
  934. /// - Note: Also calls `updateDownloadProgress`.
  935. ///
  936. /// - Parameter data: The `Data` received.
  937. func didReceive(data: Data) {
  938. $dataMutableState.write { mutableState in
  939. if mutableState.data == nil {
  940. mutableState.data = data
  941. } else {
  942. mutableState.data?.append(data)
  943. }
  944. }
  945. updateDownloadProgress()
  946. }
  947. func didReceiveResponse(_ response: HTTPURLResponse, completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) {
  948. $dataMutableState.read { dataMutableState in
  949. guard let httpResponseHandler = dataMutableState.httpResponseHandler else {
  950. underlyingQueue.async { completionHandler(.allow) }
  951. return
  952. }
  953. httpResponseHandler.queue.async {
  954. httpResponseHandler.handler(response) { disposition in
  955. if disposition == .cancel {
  956. self.$mutableState.write { mutableState in
  957. mutableState.state = .cancelled
  958. mutableState.error = mutableState.error ?? AFError.explicitlyCancelled
  959. }
  960. }
  961. self.underlyingQueue.async {
  962. completionHandler(disposition.sessionDisposition)
  963. }
  964. }
  965. }
  966. }
  967. }
  968. override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask {
  969. let copiedRequest = request
  970. return session.dataTask(with: copiedRequest)
  971. }
  972. /// Called to update the `downloadProgress` of the instance.
  973. func updateDownloadProgress() {
  974. let totalBytesReceived = Int64(data?.count ?? 0)
  975. let totalBytesExpected = task?.response?.expectedContentLength ?? NSURLSessionTransferSizeUnknown
  976. downloadProgress.totalUnitCount = totalBytesExpected
  977. downloadProgress.completedUnitCount = totalBytesReceived
  978. downloadProgressHandler?.queue.async { self.downloadProgressHandler?.handler(self.downloadProgress) }
  979. }
  980. /// Validates the request, using the specified closure.
  981. ///
  982. /// - Note: If validation fails, subsequent calls to response handlers will have an associated error.
  983. ///
  984. /// - Parameter validation: `Validation` closure used to validate the response.
  985. ///
  986. /// - Returns: The instance.
  987. @discardableResult
  988. public func validate(_ validation: @escaping Validation) -> Self {
  989. let validator: () -> Void = { [unowned self] in
  990. guard error == nil, let response = response else { return }
  991. let result = validation(request, response, data)
  992. if case let .failure(error) = result { self.error = error.asAFError(or: .responseValidationFailed(reason: .customValidationFailed(error: error))) }
  993. eventMonitor?.request(self,
  994. didValidateRequest: request,
  995. response: response,
  996. data: data,
  997. withResult: result)
  998. }
  999. $validators.write { $0.append(validator) }
  1000. return self
  1001. }
  1002. /// Sets a closure called whenever the `DataRequest` produces an `HTTPURLResponse` and providing a completion
  1003. /// handler to return a `ResponseDisposition` value.
  1004. ///
  1005. /// - Parameters:
  1006. /// - queue: `DispatchQueue` on which the closure will be called. `.main` by default.
  1007. /// - handler: Closure called when the instance produces an `HTTPURLResponse`. The `completionHandler` provided
  1008. /// MUST be called, otherwise the request will never complete.
  1009. ///
  1010. /// - Returns: The instance.
  1011. @_disfavoredOverload
  1012. @discardableResult
  1013. public func onHTTPResponse(
  1014. on queue: DispatchQueue = .main,
  1015. perform handler: @escaping (_ response: HTTPURLResponse,
  1016. _ completionHandler: @escaping (ResponseDisposition) -> Void) -> Void
  1017. ) -> Self {
  1018. $dataMutableState.write { mutableState in
  1019. mutableState.httpResponseHandler = (queue, handler)
  1020. }
  1021. return self
  1022. }
  1023. /// Sets a closure called whenever the `DataRequest` produces an `HTTPURLResponse`.
  1024. ///
  1025. /// - Parameters:
  1026. /// - queue: `DispatchQueue` on which the closure will be called. `.main` by default.
  1027. /// - handler: Closure called when the instance produces an `HTTPURLResponse`.
  1028. ///
  1029. /// - Returns: The instance.
  1030. @discardableResult
  1031. public func onHTTPResponse(on queue: DispatchQueue = .main,
  1032. perform handler: @escaping (HTTPURLResponse) -> Void) -> Self {
  1033. onHTTPResponse(on: queue) { response, completionHandler in
  1034. handler(response)
  1035. completionHandler(.allow)
  1036. }
  1037. return self
  1038. }
  1039. }
  1040. // MARK: - DataStreamRequest
  1041. /// `Request` subclass which streams HTTP response `Data` through a `Handler` closure.
  1042. public final class DataStreamRequest: Request {
  1043. /// Closure type handling `DataStreamRequest.Stream` values.
  1044. public typealias Handler<Success, Failure: Error> = (Stream<Success, Failure>) throws -> Void
  1045. /// Type encapsulating an `Event` as it flows through the stream, as well as a `CancellationToken` which can be used
  1046. /// to stop the stream at any time.
  1047. public struct Stream<Success, Failure: Error> {
  1048. /// Latest `Event` from the stream.
  1049. public let event: Event<Success, Failure>
  1050. /// Token used to cancel the stream.
  1051. public let token: CancellationToken
  1052. /// Cancel the ongoing stream by canceling the underlying `DataStreamRequest`.
  1053. public func cancel() {
  1054. token.cancel()
  1055. }
  1056. }
  1057. /// Type representing an event flowing through the stream. Contains either the `Result` of processing streamed
  1058. /// `Data` or the completion of the stream.
  1059. public enum Event<Success, Failure: Error> {
  1060. /// Output produced every time the instance receives additional `Data`. The associated value contains the
  1061. /// `Result` of processing the incoming `Data`.
  1062. case stream(Result<Success, Failure>)
  1063. /// Output produced when the instance has completed, whether due to stream end, cancellation, or an error.
  1064. /// Associated `Completion` value contains the final state.
  1065. case complete(Completion)
  1066. }
  1067. /// Value containing the state of a `DataStreamRequest` when the stream was completed.
  1068. public struct Completion {
  1069. /// Last `URLRequest` issued by the instance.
  1070. public let request: URLRequest?
  1071. /// Last `HTTPURLResponse` received by the instance.
  1072. public let response: HTTPURLResponse?
  1073. /// Last `URLSessionTaskMetrics` produced for the instance.
  1074. public let metrics: URLSessionTaskMetrics?
  1075. /// `AFError` produced for the instance, if any.
  1076. public let error: AFError?
  1077. }
  1078. /// Type used to cancel an ongoing stream.
  1079. public struct CancellationToken {
  1080. weak var request: DataStreamRequest?
  1081. init(_ request: DataStreamRequest) {
  1082. self.request = request
  1083. }
  1084. /// Cancel the ongoing stream by canceling the underlying `DataStreamRequest`.
  1085. public func cancel() {
  1086. request?.cancel()
  1087. }
  1088. }
  1089. /// `URLRequestConvertible` value used to create `URLRequest`s for this instance.
  1090. public let convertible: URLRequestConvertible
  1091. /// Whether or not the instance will be cancelled if stream parsing encounters an error.
  1092. public let automaticallyCancelOnStreamError: Bool
  1093. /// Internal mutable state specific to this type.
  1094. struct StreamMutableState {
  1095. /// `OutputStream` bound to the `InputStream` produced by `asInputStream`, if it has been called.
  1096. var outputStream: OutputStream?
  1097. /// Stream closures called as `Data` is received.
  1098. var streams: [(_ data: Data) -> Void] = []
  1099. /// Number of currently executing streams. Used to ensure completions are only fired after all streams are
  1100. /// enqueued.
  1101. var numberOfExecutingStreams = 0
  1102. /// Completion calls enqueued while streams are still executing.
  1103. var enqueuedCompletionEvents: [() -> Void] = []
  1104. /// Handler for any `HTTPURLResponse`s received.
  1105. var httpResponseHandler: (queue: DispatchQueue,
  1106. handler: (_ response: HTTPURLResponse,
  1107. _ completionHandler: @escaping (ResponseDisposition) -> Void) -> Void)?
  1108. }
  1109. @Protected
  1110. var streamMutableState = StreamMutableState()
  1111. /// Creates a `DataStreamRequest` using the provided parameters.
  1112. ///
  1113. /// - Parameters:
  1114. /// - id: `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()`
  1115. /// by default.
  1116. /// - convertible: `URLRequestConvertible` value used to create `URLRequest`s for this
  1117. /// instance.
  1118. /// - automaticallyCancelOnStreamError: `Bool` indicating whether the instance will be cancelled when an `Error`
  1119. /// is thrown while serializing stream `Data`.
  1120. /// - underlyingQueue: `DispatchQueue` on which all internal `Request` work is performed.
  1121. /// - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default
  1122. /// targets
  1123. /// `underlyingQueue`, but can be passed another queue from a `Session`.
  1124. /// - eventMonitor: `EventMonitor` called for event callbacks from internal `Request` actions.
  1125. /// - interceptor: `RequestInterceptor` used throughout the request lifecycle.
  1126. /// - delegate: `RequestDelegate` that provides an interface to actions not performed by
  1127. /// the `Request`.
  1128. init(id: UUID = UUID(),
  1129. convertible: URLRequestConvertible,
  1130. automaticallyCancelOnStreamError: Bool,
  1131. underlyingQueue: DispatchQueue,
  1132. serializationQueue: DispatchQueue,
  1133. eventMonitor: EventMonitor?,
  1134. interceptor: RequestInterceptor?,
  1135. delegate: RequestDelegate) {
  1136. self.convertible = convertible
  1137. self.automaticallyCancelOnStreamError = automaticallyCancelOnStreamError
  1138. super.init(id: id,
  1139. underlyingQueue: underlyingQueue,
  1140. serializationQueue: serializationQueue,
  1141. eventMonitor: eventMonitor,
  1142. interceptor: interceptor,
  1143. delegate: delegate)
  1144. }
  1145. override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask {
  1146. let copiedRequest = request
  1147. return session.dataTask(with: copiedRequest)
  1148. }
  1149. override func finish(error: AFError? = nil) {
  1150. $streamMutableState.write { state in
  1151. state.outputStream?.close()
  1152. }
  1153. super.finish(error: error)
  1154. }
  1155. func didReceive(data: Data) {
  1156. $streamMutableState.write { state in
  1157. #if !canImport(FoundationNetworking) // If we not using swift-corelibs-foundation.
  1158. if let stream = state.outputStream {
  1159. underlyingQueue.async {
  1160. var bytes = Array(data)
  1161. stream.write(&bytes, maxLength: bytes.count)
  1162. }
  1163. }
  1164. #endif
  1165. state.numberOfExecutingStreams += state.streams.count
  1166. let localState = state
  1167. underlyingQueue.async { localState.streams.forEach { $0(data) } }
  1168. }
  1169. }
  1170. func didReceiveResponse(_ response: HTTPURLResponse, completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) {
  1171. $streamMutableState.read { dataMutableState in
  1172. guard let httpResponseHandler = dataMutableState.httpResponseHandler else {
  1173. underlyingQueue.async { completionHandler(.allow) }
  1174. return
  1175. }
  1176. httpResponseHandler.queue.async {
  1177. httpResponseHandler.handler(response) { disposition in
  1178. if disposition == .cancel {
  1179. self.$mutableState.write { mutableState in
  1180. mutableState.state = .cancelled
  1181. mutableState.error = mutableState.error ?? AFError.explicitlyCancelled
  1182. }
  1183. }
  1184. self.underlyingQueue.async {
  1185. completionHandler(disposition.sessionDisposition)
  1186. }
  1187. }
  1188. }
  1189. }
  1190. }
  1191. /// Validates the `URLRequest` and `HTTPURLResponse` received for the instance using the provided `Validation` closure.
  1192. ///
  1193. /// - Parameter validation: `Validation` closure used to validate the request and response.
  1194. ///
  1195. /// - Returns: The `DataStreamRequest`.
  1196. @discardableResult
  1197. public func validate(_ validation: @escaping Validation) -> Self {
  1198. let validator: () -> Void = { [unowned self] in
  1199. guard error == nil, let response = response else { return }
  1200. let result = validation(request, response)
  1201. if case let .failure(error) = result {
  1202. self.error = error.asAFError(or: .responseValidationFailed(reason: .customValidationFailed(error: error)))
  1203. }
  1204. eventMonitor?.request(self,
  1205. didValidateRequest: request,
  1206. response: response,
  1207. withResult: result)
  1208. }
  1209. $validators.write { $0.append(validator) }
  1210. return self
  1211. }
  1212. #if !canImport(FoundationNetworking) // If we not using swift-corelibs-foundation.
  1213. /// Produces an `InputStream` that receives the `Data` received by the instance.
  1214. ///
  1215. /// - Note: The `InputStream` produced by this method must have `open()` called before being able to read `Data`.
  1216. /// Additionally, this method will automatically call `resume()` on the instance, regardless of whether or
  1217. /// not the creating session has `startRequestsImmediately` set to `true`.
  1218. ///
  1219. /// - Parameter bufferSize: Size, in bytes, of the buffer between the `OutputStream` and `InputStream`.
  1220. ///
  1221. /// - Returns: The `InputStream` bound to the internal `OutboundStream`.
  1222. public func asInputStream(bufferSize: Int = 1024) -> InputStream? {
  1223. defer { resume() }
  1224. var inputStream: InputStream?
  1225. $streamMutableState.write { state in
  1226. Foundation.Stream.getBoundStreams(withBufferSize: bufferSize,
  1227. inputStream: &inputStream,
  1228. outputStream: &state.outputStream)
  1229. state.outputStream?.open()
  1230. }
  1231. return inputStream
  1232. }
  1233. #endif
  1234. /// Sets a closure called whenever the `DataRequest` produces an `HTTPURLResponse` and providing a completion
  1235. /// handler to return a `ResponseDisposition` value.
  1236. ///
  1237. /// - Parameters:
  1238. /// - queue: `DispatchQueue` on which the closure will be called. `.main` by default.
  1239. /// - handler: Closure called when the instance produces an `HTTPURLResponse`. The `completionHandler` provided
  1240. /// MUST be called, otherwise the request will never complete.
  1241. ///
  1242. /// - Returns: The instance.
  1243. @_disfavoredOverload
  1244. @discardableResult
  1245. public func onHTTPResponse(
  1246. on queue: DispatchQueue = .main,
  1247. perform handler: @escaping (_ response: HTTPURLResponse,
  1248. _ completionHandler: @escaping (ResponseDisposition) -> Void) -> Void
  1249. ) -> Self {
  1250. $streamMutableState.write { mutableState in
  1251. mutableState.httpResponseHandler = (queue, handler)
  1252. }
  1253. return self
  1254. }
  1255. /// Sets a closure called whenever the `DataRequest` produces an `HTTPURLResponse`.
  1256. ///
  1257. /// - Parameters:
  1258. /// - queue: `DispatchQueue` on which the closure will be called. `.main` by default.
  1259. /// - handler: Closure called when the instance produces an `HTTPURLResponse`.
  1260. ///
  1261. /// - Returns: The instance.
  1262. @discardableResult
  1263. public func onHTTPResponse(on queue: DispatchQueue = .main,
  1264. perform handler: @escaping (HTTPURLResponse) -> Void) -> Self {
  1265. onHTTPResponse(on: queue) { response, completionHandler in
  1266. handler(response)
  1267. completionHandler(.allow)
  1268. }
  1269. return self
  1270. }
  1271. func capturingError(from closure: () throws -> Void) {
  1272. do {
  1273. try closure()
  1274. } catch {
  1275. self.error = error.asAFError(or: .responseSerializationFailed(reason: .customSerializationFailed(error: error)))
  1276. cancel()
  1277. }
  1278. }
  1279. func appendStreamCompletion<Success, Failure>(on queue: DispatchQueue,
  1280. stream: @escaping Handler<Success, Failure>) {
  1281. appendResponseSerializer {
  1282. self.underlyingQueue.async {
  1283. self.responseSerializerDidComplete {
  1284. self.$streamMutableState.write { state in
  1285. guard state.numberOfExecutingStreams == 0 else {
  1286. state.enqueuedCompletionEvents.append {
  1287. self.enqueueCompletion(on: queue, stream: stream)
  1288. }
  1289. return
  1290. }
  1291. self.enqueueCompletion(on: queue, stream: stream)
  1292. }
  1293. }
  1294. }
  1295. }
  1296. }
  1297. func enqueueCompletion<Success, Failure>(on queue: DispatchQueue,
  1298. stream: @escaping Handler<Success, Failure>) {
  1299. queue.async {
  1300. do {
  1301. let completion = Completion(request: self.request,
  1302. response: self.response,
  1303. metrics: self.metrics,
  1304. error: self.error)
  1305. try stream(.init(event: .complete(completion), token: .init(self)))
  1306. } catch {
  1307. // Ignore error, as errors on Completion can't be handled anyway.
  1308. }
  1309. }
  1310. }
  1311. }
  1312. extension DataStreamRequest.Stream {
  1313. /// Incoming `Result` values from `Event.stream`.
  1314. public var result: Result<Success, Failure>? {
  1315. guard case let .stream(result) = event else { return nil }
  1316. return result
  1317. }
  1318. /// `Success` value of the instance, if any.
  1319. public var value: Success? {
  1320. guard case let .success(value) = result else { return nil }
  1321. return value
  1322. }
  1323. /// `Failure` value of the instance, if any.
  1324. public var error: Failure? {
  1325. guard case let .failure(error) = result else { return nil }
  1326. return error
  1327. }
  1328. /// `Completion` value of the instance, if any.
  1329. public var completion: DataStreamRequest.Completion? {
  1330. guard case let .complete(completion) = event else { return nil }
  1331. return completion
  1332. }
  1333. }
  1334. // MARK: - DownloadRequest
  1335. /// `Request` subclass which downloads `Data` to a file on disk using `URLSessionDownloadTask`.
  1336. public class DownloadRequest: Request {
  1337. /// A set of options to be executed prior to moving a downloaded file from the temporary `URL` to the destination
  1338. /// `URL`.
  1339. public struct Options: OptionSet {
  1340. /// Specifies that intermediate directories for the destination URL should be created.
  1341. public static let createIntermediateDirectories = Options(rawValue: 1 << 0)
  1342. /// Specifies that any previous file at the destination `URL` should be removed.
  1343. public static let removePreviousFile = Options(rawValue: 1 << 1)
  1344. public let rawValue: Int
  1345. public init(rawValue: Int) {
  1346. self.rawValue = rawValue
  1347. }
  1348. }
  1349. // MARK: Destination
  1350. /// A closure executed once a `DownloadRequest` has successfully completed in order to determine where to move the
  1351. /// temporary file written to during the download process. The closure takes two arguments: the temporary file URL
  1352. /// and the `HTTPURLResponse`, and returns two values: the file URL where the temporary file should be moved and
  1353. /// the options defining how the file should be moved.
  1354. ///
  1355. /// - Note: Downloads from a local `file://` `URL`s do not use the `Destination` closure, as those downloads do not
  1356. /// return an `HTTPURLResponse`. Instead the file is merely moved within the temporary directory.
  1357. public typealias Destination = (_ temporaryURL: URL,
  1358. _ response: HTTPURLResponse) -> (destinationURL: URL, options: Options)
  1359. /// Creates a download file destination closure which uses the default file manager to move the temporary file to a
  1360. /// file URL in the first available directory with the specified search path directory and search path domain mask.
  1361. ///
  1362. /// - Parameters:
  1363. /// - directory: The search path directory. `.documentDirectory` by default.
  1364. /// - domain: The search path domain mask. `.userDomainMask` by default.
  1365. /// - options: `DownloadRequest.Options` used when moving the downloaded file to its destination. None by
  1366. /// default.
  1367. /// - Returns: The `Destination` closure.
  1368. public class func suggestedDownloadDestination(for directory: FileManager.SearchPathDirectory = .documentDirectory,
  1369. in domain: FileManager.SearchPathDomainMask = .userDomainMask,
  1370. options: Options = []) -> Destination {
  1371. { temporaryURL, response in
  1372. let directoryURLs = FileManager.default.urls(for: directory, in: domain)
  1373. let url = directoryURLs.first?.appendingPathComponent(response.suggestedFilename!) ?? temporaryURL
  1374. return (url, options)
  1375. }
  1376. }
  1377. /// Default `Destination` used by Alamofire to ensure all downloads persist. This `Destination` prepends
  1378. /// `Alamofire_` to the automatically generated download name and moves it within the temporary directory. Files
  1379. /// with this destination must be additionally moved if they should survive the system reclamation of temporary
  1380. /// space.
  1381. static let defaultDestination: Destination = { url, _ in
  1382. (defaultDestinationURL(url), [])
  1383. }
  1384. /// Default `URL` creation closure. Creates a `URL` in the temporary directory with `Alamofire_` prepended to the
  1385. /// provided file name.
  1386. static let defaultDestinationURL: (URL) -> URL = { url in
  1387. let filename = "Alamofire_\(url.lastPathComponent)"
  1388. let destination = url.deletingLastPathComponent().appendingPathComponent(filename)
  1389. return destination
  1390. }
  1391. // MARK: Downloadable
  1392. /// Type describing the source used to create the underlying `URLSessionDownloadTask`.
  1393. public enum Downloadable {
  1394. /// Download should be started from the `URLRequest` produced by the associated `URLRequestConvertible` value.
  1395. case request(URLRequestConvertible)
  1396. /// Download should be started from the associated resume `Data` value.
  1397. case resumeData(Data)
  1398. }
  1399. // MARK: Mutable State
  1400. /// Type containing all mutable state for `DownloadRequest` instances.
  1401. private struct DownloadRequestMutableState {
  1402. /// Possible resume `Data` produced when cancelling the instance.
  1403. var resumeData: Data?
  1404. /// `URL` to which `Data` is being downloaded.
  1405. var fileURL: URL?
  1406. }
  1407. /// Protected mutable state specific to `DownloadRequest`.
  1408. @Protected
  1409. private var mutableDownloadState = DownloadRequestMutableState()
  1410. /// If the download is resumable and is eventually cancelled or fails, this value may be used to resume the download
  1411. /// using the `download(resumingWith data:)` API.
  1412. ///
  1413. /// - Note: For more information about `resumeData`, see [Apple's documentation](https://developer.apple.com/documentation/foundation/urlsessiondownloadtask/1411634-cancel).
  1414. public var resumeData: Data? {
  1415. #if !canImport(FoundationNetworking) // If we not using swift-corelibs-foundation.
  1416. return $mutableDownloadState.resumeData ?? error?.downloadResumeData
  1417. #else
  1418. return $mutableDownloadState.resumeData
  1419. #endif
  1420. }
  1421. /// If the download is successful, the `URL` where the file was downloaded.
  1422. public var fileURL: URL? { $mutableDownloadState.fileURL }
  1423. // MARK: Initial State
  1424. /// `Downloadable` value used for this instance.
  1425. public let downloadable: Downloadable
  1426. /// The `Destination` to which the downloaded file is moved.
  1427. let destination: Destination
  1428. /// Creates a `DownloadRequest` using the provided parameters.
  1429. ///
  1430. /// - Parameters:
  1431. /// - id: `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()` by default.
  1432. /// - downloadable: `Downloadable` value used to create `URLSessionDownloadTasks` for the instance.
  1433. /// - underlyingQueue: `DispatchQueue` on which all internal `Request` work is performed.
  1434. /// - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default targets
  1435. /// `underlyingQueue`, but can be passed another queue from a `Session`.
  1436. /// - eventMonitor: `EventMonitor` called for event callbacks from internal `Request` actions.
  1437. /// - interceptor: `RequestInterceptor` used throughout the request lifecycle.
  1438. /// - delegate: `RequestDelegate` that provides an interface to actions not performed by the `Request`
  1439. /// - destination: `Destination` closure used to move the downloaded file to its final location.
  1440. init(id: UUID = UUID(),
  1441. downloadable: Downloadable,
  1442. underlyingQueue: DispatchQueue,
  1443. serializationQueue: DispatchQueue,
  1444. eventMonitor: EventMonitor?,
  1445. interceptor: RequestInterceptor?,
  1446. delegate: RequestDelegate,
  1447. destination: @escaping Destination) {
  1448. self.downloadable = downloadable
  1449. self.destination = destination
  1450. super.init(id: id,
  1451. underlyingQueue: underlyingQueue,
  1452. serializationQueue: serializationQueue,
  1453. eventMonitor: eventMonitor,
  1454. interceptor: interceptor,
  1455. delegate: delegate)
  1456. }
  1457. override func reset() {
  1458. super.reset()
  1459. $mutableDownloadState.write {
  1460. $0.resumeData = nil
  1461. $0.fileURL = nil
  1462. }
  1463. }
  1464. /// Called when a download has finished.
  1465. ///
  1466. /// - Parameters:
  1467. /// - task: `URLSessionTask` that finished the download.
  1468. /// - result: `Result` of the automatic move to `destination`.
  1469. func didFinishDownloading(using task: URLSessionTask, with result: Result<URL, AFError>) {
  1470. eventMonitor?.request(self, didFinishDownloadingUsing: task, with: result)
  1471. switch result {
  1472. case let .success(url): $mutableDownloadState.fileURL = url
  1473. case let .failure(error): self.error = error
  1474. }
  1475. }
  1476. /// Updates the `downloadProgress` using the provided values.
  1477. ///
  1478. /// - Parameters:
  1479. /// - bytesWritten: Total bytes written so far.
  1480. /// - totalBytesExpectedToWrite: Total bytes expected to write.
  1481. func updateDownloadProgress(bytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
  1482. downloadProgress.totalUnitCount = totalBytesExpectedToWrite
  1483. downloadProgress.completedUnitCount += bytesWritten
  1484. downloadProgressHandler?.queue.async { self.downloadProgressHandler?.handler(self.downloadProgress) }
  1485. }
  1486. override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask {
  1487. session.downloadTask(with: request)
  1488. }
  1489. /// Creates a `URLSessionTask` from the provided resume data.
  1490. ///
  1491. /// - Parameters:
  1492. /// - data: `Data` used to resume the download.
  1493. /// - session: `URLSession` used to create the `URLSessionTask`.
  1494. ///
  1495. /// - Returns: The `URLSessionTask` created.
  1496. public func task(forResumeData data: Data, using session: URLSession) -> URLSessionTask {
  1497. session.downloadTask(withResumeData: data)
  1498. }
  1499. /// Cancels the instance. Once cancelled, a `DownloadRequest` can no longer be resumed or suspended.
  1500. ///
  1501. /// - Note: This method will NOT produce resume data. If you wish to cancel and produce resume data, use
  1502. /// `cancel(producingResumeData:)` or `cancel(byProducingResumeData:)`.
  1503. ///
  1504. /// - Returns: The instance.
  1505. @discardableResult
  1506. override public func cancel() -> Self {
  1507. cancel(producingResumeData: false)
  1508. }
  1509. /// Cancels the instance, optionally producing resume data. Once cancelled, a `DownloadRequest` can no longer be
  1510. /// resumed or suspended.
  1511. ///
  1512. /// - Note: If `producingResumeData` is `true`, the `resumeData` property will be populated with any resume data, if
  1513. /// available.
  1514. ///
  1515. /// - Returns: The instance.
  1516. @discardableResult
  1517. public func cancel(producingResumeData shouldProduceResumeData: Bool) -> Self {
  1518. cancel(optionallyProducingResumeData: shouldProduceResumeData ? { _ in } : nil)
  1519. }
  1520. /// Cancels the instance while producing resume data. Once cancelled, a `DownloadRequest` can no longer be resumed
  1521. /// or suspended.
  1522. ///
  1523. /// - Note: The resume data passed to the completion handler will also be available on the instance's `resumeData`
  1524. /// property.
  1525. ///
  1526. /// - Parameter completionHandler: The completion handler that is called when the download has been successfully
  1527. /// cancelled. It is not guaranteed to be called on a particular queue, so you may
  1528. /// want use an appropriate queue to perform your work.
  1529. ///
  1530. /// - Returns: The instance.
  1531. @discardableResult
  1532. public func cancel(byProducingResumeData completionHandler: @escaping (_ data: Data?) -> Void) -> Self {
  1533. cancel(optionallyProducingResumeData: completionHandler)
  1534. }
  1535. /// Internal implementation of cancellation that optionally takes a resume data handler. If no handler is passed,
  1536. /// cancellation is performed without producing resume data.
  1537. ///
  1538. /// - Parameter completionHandler: Optional resume data handler.
  1539. ///
  1540. /// - Returns: The instance.
  1541. private func cancel(optionallyProducingResumeData completionHandler: ((_ resumeData: Data?) -> Void)?) -> Self {
  1542. $mutableState.write { mutableState in
  1543. guard mutableState.state.canTransitionTo(.cancelled) else { return }
  1544. mutableState.state = .cancelled
  1545. underlyingQueue.async { self.didCancel() }
  1546. guard let task = mutableState.tasks.last as? URLSessionDownloadTask, task.state != .completed else {
  1547. underlyingQueue.async { self.finish() }
  1548. return
  1549. }
  1550. if let completionHandler = completionHandler {
  1551. // Resume to ensure metrics are gathered.
  1552. task.resume()
  1553. task.cancel { resumeData in
  1554. self.$mutableDownloadState.resumeData = resumeData
  1555. self.underlyingQueue.async { self.didCancelTask(task) }
  1556. completionHandler(resumeData)
  1557. }
  1558. } else {
  1559. // Resume to ensure metrics are gathered.
  1560. task.resume()
  1561. task.cancel()
  1562. self.underlyingQueue.async { self.didCancelTask(task) }
  1563. }
  1564. }
  1565. return self
  1566. }
  1567. /// Validates the request, using the specified closure.
  1568. ///
  1569. /// - Note: If validation fails, subsequent calls to response handlers will have an associated error.
  1570. ///
  1571. /// - Parameter validation: `Validation` closure to validate the response.
  1572. ///
  1573. /// - Returns: The instance.
  1574. @discardableResult
  1575. public func validate(_ validation: @escaping Validation) -> Self {
  1576. let validator: () -> Void = { [unowned self] in
  1577. guard error == nil, let response = response else { return }
  1578. let result = validation(request, response, fileURL)
  1579. if case let .failure(error) = result {
  1580. self.error = error.asAFError(or: .responseValidationFailed(reason: .customValidationFailed(error: error)))
  1581. }
  1582. eventMonitor?.request(self,
  1583. didValidateRequest: request,
  1584. response: response,
  1585. fileURL: fileURL,
  1586. withResult: result)
  1587. }
  1588. $validators.write { $0.append(validator) }
  1589. return self
  1590. }
  1591. }
  1592. // MARK: - UploadRequest
  1593. /// `DataRequest` subclass which handles `Data` upload from memory, file, or stream using `URLSessionUploadTask`.
  1594. public class UploadRequest: DataRequest {
  1595. /// Type describing the origin of the upload, whether `Data`, file, or stream.
  1596. public enum Uploadable {
  1597. /// Upload from the provided `Data` value.
  1598. case data(Data)
  1599. /// Upload from the provided file `URL`, as well as a `Bool` determining whether the source file should be
  1600. /// automatically removed once uploaded.
  1601. case file(URL, shouldRemove: Bool)
  1602. /// Upload from the provided `InputStream`.
  1603. case stream(InputStream)
  1604. }
  1605. // MARK: Initial State
  1606. /// The `UploadableConvertible` value used to produce the `Uploadable` value for this instance.
  1607. public let upload: UploadableConvertible
  1608. /// `FileManager` used to perform cleanup tasks, including the removal of multipart form encoded payloads written
  1609. /// to disk.
  1610. public let fileManager: FileManager
  1611. // MARK: Mutable State
  1612. /// `Uploadable` value used by the instance.
  1613. public var uploadable: Uploadable?
  1614. /// Creates an `UploadRequest` using the provided parameters.
  1615. ///
  1616. /// - Parameters:
  1617. /// - id: `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()` by default.
  1618. /// - convertible: `UploadConvertible` value used to determine the type of upload to be performed.
  1619. /// - underlyingQueue: `DispatchQueue` on which all internal `Request` work is performed.
  1620. /// - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default targets
  1621. /// `underlyingQueue`, but can be passed another queue from a `Session`.
  1622. /// - eventMonitor: `EventMonitor` called for event callbacks from internal `Request` actions.
  1623. /// - interceptor: `RequestInterceptor` used throughout the request lifecycle.
  1624. /// - fileManager: `FileManager` used to perform cleanup tasks, including the removal of multipart form
  1625. /// encoded payloads written to disk.
  1626. /// - delegate: `RequestDelegate` that provides an interface to actions not performed by the `Request`.
  1627. init(id: UUID = UUID(),
  1628. convertible: UploadConvertible,
  1629. underlyingQueue: DispatchQueue,
  1630. serializationQueue: DispatchQueue,
  1631. eventMonitor: EventMonitor?,
  1632. interceptor: RequestInterceptor?,
  1633. fileManager: FileManager,
  1634. delegate: RequestDelegate) {
  1635. upload = convertible
  1636. self.fileManager = fileManager
  1637. super.init(id: id,
  1638. convertible: convertible,
  1639. underlyingQueue: underlyingQueue,
  1640. serializationQueue: serializationQueue,
  1641. eventMonitor: eventMonitor,
  1642. interceptor: interceptor,
  1643. delegate: delegate)
  1644. }
  1645. /// Called when the `Uploadable` value has been created from the `UploadConvertible`.
  1646. ///
  1647. /// - Parameter uploadable: The `Uploadable` that was created.
  1648. func didCreateUploadable(_ uploadable: Uploadable) {
  1649. self.uploadable = uploadable
  1650. eventMonitor?.request(self, didCreateUploadable: uploadable)
  1651. }
  1652. /// Called when the `Uploadable` value could not be created.
  1653. ///
  1654. /// - Parameter error: `AFError` produced by the failure.
  1655. func didFailToCreateUploadable(with error: AFError) {
  1656. self.error = error
  1657. eventMonitor?.request(self, didFailToCreateUploadableWithError: error)
  1658. retryOrFinish(error: error)
  1659. }
  1660. override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask {
  1661. guard let uploadable = uploadable else {
  1662. fatalError("Attempting to create a URLSessionUploadTask when Uploadable value doesn't exist.")
  1663. }
  1664. switch uploadable {
  1665. case let .data(data): return session.uploadTask(with: request, from: data)
  1666. case let .file(url, _): return session.uploadTask(with: request, fromFile: url)
  1667. case .stream: return session.uploadTask(withStreamedRequest: request)
  1668. }
  1669. }
  1670. override func reset() {
  1671. // Uploadable must be recreated on every retry.
  1672. uploadable = nil
  1673. super.reset()
  1674. }
  1675. /// Produces the `InputStream` from `uploadable`, if it can.
  1676. ///
  1677. /// - Note: Calling this method with a non-`.stream` `Uploadable` is a logic error and will crash.
  1678. ///
  1679. /// - Returns: The `InputStream`.
  1680. func inputStream() -> InputStream {
  1681. guard let uploadable = uploadable else {
  1682. fatalError("Attempting to access the input stream but the uploadable doesn't exist.")
  1683. }
  1684. guard case let .stream(stream) = uploadable else {
  1685. fatalError("Attempted to access the stream of an UploadRequest that wasn't created with one.")
  1686. }
  1687. eventMonitor?.request(self, didProvideInputStream: stream)
  1688. return stream
  1689. }
  1690. override public func cleanup() {
  1691. defer { super.cleanup() }
  1692. guard
  1693. let uploadable = uploadable,
  1694. case let .file(url, shouldRemove) = uploadable,
  1695. shouldRemove
  1696. else { return }
  1697. try? fileManager.removeItem(at: url)
  1698. }
  1699. }
  1700. /// A type that can produce an `UploadRequest.Uploadable` value.
  1701. public protocol UploadableConvertible {
  1702. /// Produces an `UploadRequest.Uploadable` value from the instance.
  1703. ///
  1704. /// - Returns: The `UploadRequest.Uploadable`.
  1705. /// - Throws: Any `Error` produced during creation.
  1706. func createUploadable() throws -> UploadRequest.Uploadable
  1707. }
  1708. extension UploadRequest.Uploadable: UploadableConvertible {
  1709. public func createUploadable() throws -> UploadRequest.Uploadable {
  1710. self
  1711. }
  1712. }
  1713. /// A type that can be converted to an upload, whether from an `UploadRequest.Uploadable` or `URLRequestConvertible`.
  1714. public protocol UploadConvertible: UploadableConvertible & URLRequestConvertible {}