Repositorio del curso CCOM4030 el semestre B91 del proyecto Trolley

Request.swift 61KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461
  1. //
  2. // Request.swift
  3. //
  4. // Copyright (c) 2014-2018 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. /// Closure called when the `Request` is able to create a cURL description of itself.
  89. var cURLHandler: ((String) -> Void)?
  90. /// Response serialization closures that handle response parsing.
  91. var responseSerializers: [() -> Void] = []
  92. /// Response serialization completion closures executed once all response serializers are complete.
  93. var responseSerializerCompletions: [() -> Void] = []
  94. /// Whether response serializer processing is finished.
  95. var responseSerializerProcessingFinished = false
  96. /// `URLCredential` used for authentication challenges.
  97. var credential: URLCredential?
  98. /// All `URLRequest`s created by Alamofire on behalf of the `Request`.
  99. var requests: [URLRequest] = []
  100. /// All `URLSessionTask`s created by Alamofire on behalf of the `Request`.
  101. var tasks: [URLSessionTask] = []
  102. /// All `URLSessionTaskMetrics` values gathered by Alamofire on behalf of the `Request`. Should correspond
  103. /// exactly the the `tasks` created.
  104. var metrics: [URLSessionTaskMetrics] = []
  105. /// Number of times any retriers provided retried the `Request`.
  106. var retryCount = 0
  107. /// Final `AFError` for the `Request`, whether from various internal Alamofire calls or as a result of a `task`.
  108. var error: AFError?
  109. }
  110. /// Protected `MutableState` value that provides thread-safe access to state values.
  111. fileprivate let protectedMutableState: Protector<MutableState> = Protector(MutableState())
  112. /// `State` of the `Request`.
  113. public var state: State { return protectedMutableState.directValue.state }
  114. /// Returns whether `state` is `.initialized`.
  115. public var isInitialized: Bool { return state == .initialized }
  116. /// Returns whether `state is `.resumed`.
  117. public var isResumed: Bool { return state == .resumed }
  118. /// Returns whether `state` is `.suspended`.
  119. public var isSuspended: Bool { return state == .suspended }
  120. /// Returns whether `state` is `.cancelled`.
  121. public var isCancelled: Bool { return state == .cancelled }
  122. /// Returns whether `state` is `.finished`.
  123. public var isFinished: Bool { return state == .finished }
  124. // MARK: Progress
  125. /// Closure type executed when monitoring the upload or download progress of a request.
  126. public typealias ProgressHandler = (Progress) -> Void
  127. /// `Progress` of the upload of the body of the executed `URLRequest`. Reset to `0` if the `Request` is retried.
  128. public let uploadProgress = Progress(totalUnitCount: 0)
  129. /// `Progress` of the download of any response data. Reset to `0` if the `Request` is retried.
  130. public let downloadProgress = Progress(totalUnitCount: 0)
  131. /// `ProgressHandler` called when `uploadProgress` is updated, on the provided `DispatchQueue`.
  132. fileprivate var uploadProgressHandler: (handler: ProgressHandler, queue: DispatchQueue)? {
  133. get { return protectedMutableState.directValue.uploadProgressHandler }
  134. set { protectedMutableState.write { $0.uploadProgressHandler = newValue } }
  135. }
  136. /// `ProgressHandler` called when `downloadProgress` is updated, on the provided `DispatchQueue`.
  137. fileprivate var downloadProgressHandler: (handler: ProgressHandler, queue: DispatchQueue)? {
  138. get { return protectedMutableState.directValue.downloadProgressHandler }
  139. set { protectedMutableState.write { $0.downloadProgressHandler = newValue } }
  140. }
  141. // MARK: Redirect Handling
  142. /// `RedirectHandler` set on the instance.
  143. public private(set) var redirectHandler: RedirectHandler? {
  144. get { return protectedMutableState.directValue.redirectHandler }
  145. set { protectedMutableState.write { $0.redirectHandler = newValue } }
  146. }
  147. // MARK: Cached Response Handling
  148. /// `CachedResponseHandler` set on the instance.
  149. public private(set) var cachedResponseHandler: CachedResponseHandler? {
  150. get { return protectedMutableState.directValue.cachedResponseHandler }
  151. set { protectedMutableState.write { $0.cachedResponseHandler = newValue } }
  152. }
  153. // MARK: URLCredential
  154. /// `URLCredential` used for authentication challenges. Created by calling one of the `authenticate` methods.
  155. public private(set) var credential: URLCredential? {
  156. get { return protectedMutableState.directValue.credential }
  157. set { protectedMutableState.write { $0.credential = newValue } }
  158. }
  159. // MARK: Validators
  160. /// `Validator` callback closures that store the validation calls enqueued.
  161. fileprivate var protectedValidators: Protector<[() -> Void]> = Protector([])
  162. // MARK: URLRequests
  163. /// All `URLRequests` created on behalf of the `Request`, including original and adapted requests.
  164. public var requests: [URLRequest] { return protectedMutableState.directValue.requests }
  165. /// First `URLRequest` created on behalf of the `Request`. May not be the first one actually executed.
  166. public var firstRequest: URLRequest? { return requests.first }
  167. /// Last `URLRequest` created on behalf of the `Request`.
  168. public var lastRequest: URLRequest? { return requests.last }
  169. /// Current `URLRequest` created on behalf of the `Request`.
  170. public var request: URLRequest? { return lastRequest }
  171. /// `URLRequest`s from all of the `URLSessionTask`s executed on behalf of the `Request`. May be different from
  172. /// `requests` due to `URLSession` manipulation.
  173. public var performedRequests: [URLRequest] {
  174. return protectedMutableState.read { $0.tasks.compactMap { $0.currentRequest } }
  175. }
  176. // MARK: HTTPURLResponse
  177. /// `HTTPURLResponse` received from the server, if any. If the `Request` was retried, this is the response of the
  178. /// last `URLSessionTask`.
  179. public var response: HTTPURLResponse? { return lastTask?.response as? HTTPURLResponse }
  180. // MARK: Tasks
  181. /// All `URLSessionTask`s created on behalf of the `Request`.
  182. public var tasks: [URLSessionTask] { return protectedMutableState.directValue.tasks }
  183. /// First `URLSessionTask` created on behalf of the `Request`.
  184. public var firstTask: URLSessionTask? { return tasks.first }
  185. /// Last `URLSessionTask` crated on behalf of the `Request`.
  186. public var lastTask: URLSessionTask? { return tasks.last }
  187. /// Current `URLSessionTask` created on behalf of the `Request`.
  188. public var task: URLSessionTask? { return lastTask }
  189. // MARK: Metrics
  190. /// All `URLSessionTaskMetrics` gathered on behalf of the `Request`. Should correspond to the `tasks` created.
  191. public var allMetrics: [URLSessionTaskMetrics] { return protectedMutableState.directValue.metrics }
  192. /// First `URLSessionTaskMetrics` gathered on behalf of the `Request`.
  193. public var firstMetrics: URLSessionTaskMetrics? { return allMetrics.first }
  194. /// Last `URLSessionTaskMetrics` gathered on behalf of the `Request`.
  195. public var lastMetrics: URLSessionTaskMetrics? { return allMetrics.last }
  196. /// Current `URLSessionTaskMetrics` gathered on behalf of the `Request`.
  197. public var metrics: URLSessionTaskMetrics? { return lastMetrics }
  198. // MARK: Retry Count
  199. /// Number of times the `Request` has been retried.
  200. public var retryCount: Int { return protectedMutableState.directValue.retryCount }
  201. // MARK: Error
  202. /// `Error` returned from Alamofire internally, from the network request directly, or any validators executed.
  203. public fileprivate(set) var error: AFError? {
  204. get { return protectedMutableState.directValue.error }
  205. set { protectedMutableState.write { $0.error = newValue } }
  206. }
  207. /// Default initializer for the `Request` superclass.
  208. ///
  209. /// - Parameters:
  210. /// - id: `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()` by default.
  211. /// - underlyingQueue: `DispatchQueue` on which all internal `Request` work is performed.
  212. /// - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default targets
  213. /// `underlyingQueue`, but can be passed another queue from a `Session`.
  214. /// - eventMonitor: `EventMonitor` called for event callbacks from internal `Request` actions.
  215. /// - interceptor: `RequestInterceptor` used throughout the request lifecycle.
  216. /// - delegate: `RequestDelegate` that provides an interface to actions not performed by the `Request`.
  217. init(id: UUID = UUID(),
  218. underlyingQueue: DispatchQueue,
  219. serializationQueue: DispatchQueue,
  220. eventMonitor: EventMonitor?,
  221. interceptor: RequestInterceptor?,
  222. delegate: RequestDelegate) {
  223. self.id = id
  224. self.underlyingQueue = underlyingQueue
  225. self.serializationQueue = serializationQueue
  226. self.eventMonitor = eventMonitor
  227. self.interceptor = interceptor
  228. self.delegate = delegate
  229. }
  230. // MARK: - Internal Event API
  231. // All API must be called from underlyingQueue.
  232. /// Called when an initial `URLRequest` has been created on behalf of the instance. If a `RequestAdapter` is active,
  233. /// the `URLRequest` will be adapted before being issued.
  234. ///
  235. /// - Parameter request: The `URLRequest` created.
  236. func didCreateInitialURLRequest(_ request: URLRequest) {
  237. protectedMutableState.write { $0.requests.append(request) }
  238. eventMonitor?.request(self, didCreateInitialURLRequest: request)
  239. }
  240. /// Called when initial `URLRequest` creation has failed, typically through a `URLRequestConvertible`.
  241. ///
  242. /// - Note: Triggers retry.
  243. ///
  244. /// - Parameter error: `AFError` thrown from the failed creation.
  245. func didFailToCreateURLRequest(with error: AFError) {
  246. self.error = error
  247. eventMonitor?.request(self, didFailToCreateURLRequestWithError: error)
  248. callCURLHandlerIfNecessary()
  249. retryOrFinish(error: error)
  250. }
  251. /// Called when a `RequestAdapter` has successfully adapted a `URLRequest`.
  252. ///
  253. /// - Parameters:
  254. /// - initialRequest: The `URLRequest` that was adapted.
  255. /// - adaptedRequest: The `URLRequest` returned by the `RequestAdapter`.
  256. func didAdaptInitialRequest(_ initialRequest: URLRequest, to adaptedRequest: URLRequest) {
  257. protectedMutableState.write { $0.requests.append(adaptedRequest) }
  258. eventMonitor?.request(self, didAdaptInitialRequest: initialRequest, to: adaptedRequest)
  259. }
  260. /// Called when a `RequestAdapter` fails to adapt a `URLRequest`.
  261. ///
  262. /// - Note: Triggers retry.
  263. ///
  264. /// - Parameters:
  265. /// - request: The `URLRequest` the adapter was called with.
  266. /// - error: The `AFError` returned by the `RequestAdapter`.
  267. func didFailToAdaptURLRequest(_ request: URLRequest, withError error: AFError) {
  268. self.error = error
  269. eventMonitor?.request(self, didFailToAdaptURLRequest: request, withError: error)
  270. callCURLHandlerIfNecessary()
  271. retryOrFinish(error: error)
  272. }
  273. /// Final `URLRequest` has been created for the instance.
  274. ///
  275. /// - Parameter request: The `URLRequest` created.
  276. func didCreateURLRequest(_ request: URLRequest) {
  277. eventMonitor?.request(self, didCreateURLRequest: request)
  278. callCURLHandlerIfNecessary()
  279. }
  280. /// Asynchronously calls any stored `cURLHandler` and then removes it from `mutableState`.
  281. private func callCURLHandlerIfNecessary() {
  282. protectedMutableState.write { mutableState in
  283. guard let cURLHandler = mutableState.cURLHandler else { return }
  284. self.underlyingQueue.async { cURLHandler(self.cURLDescription()) }
  285. mutableState.cURLHandler = nil
  286. }
  287. }
  288. /// Called when a `URLSessionTask` is created on behalf of the instance.
  289. ///
  290. /// - Parameter task: The `URLSessionTask` created.
  291. func didCreateTask(_ task: URLSessionTask) {
  292. protectedMutableState.write { $0.tasks.append(task) }
  293. eventMonitor?.request(self, didCreateTask: task)
  294. }
  295. /// Called when resumption is completed.
  296. func didResume() {
  297. eventMonitor?.requestDidResume(self)
  298. }
  299. /// Called when a `URLSessionTask` is resumed on behalf of the instance.
  300. ///
  301. /// - Parameter task: The `URLSessionTask` resumed.
  302. func didResumeTask(_ task: URLSessionTask) {
  303. eventMonitor?.request(self, didResumeTask: task)
  304. }
  305. /// Called when suspension is completed.
  306. func didSuspend() {
  307. eventMonitor?.requestDidSuspend(self)
  308. }
  309. /// Called when a `URLSessionTask` is suspended on behalf of the instance.
  310. ///
  311. /// - Parameter task: The `URLSessionTask` suspended.
  312. func didSuspendTask(_ task: URLSessionTask) {
  313. eventMonitor?.request(self, didSuspendTask: task)
  314. }
  315. /// Called when cancellation is completed, sets `error` to `AFError.explicitlyCancelled`.
  316. func didCancel() {
  317. error = AFError.explicitlyCancelled
  318. eventMonitor?.requestDidCancel(self)
  319. }
  320. /// Called when a `URLSessionTask` is cancelled on behalf of the instance.
  321. ///
  322. /// - Parameter task: The `URLSessionTask` cancelled.
  323. func didCancelTask(_ task: URLSessionTask) {
  324. eventMonitor?.request(self, didCancelTask: task)
  325. }
  326. /// Called when a `URLSessionTaskMetrics` value is gathered on behalf of the instance.
  327. ///
  328. /// - Parameter metrics: The `URLSessionTaskMetrics` gathered.
  329. func didGatherMetrics(_ metrics: URLSessionTaskMetrics) {
  330. protectedMutableState.write { $0.metrics.append(metrics) }
  331. eventMonitor?.request(self, didGatherMetrics: metrics)
  332. }
  333. /// Called when a `URLSessionTask` fails before it is finished, typically during certificate pinning.
  334. ///
  335. /// - Parameters:
  336. /// - task: The `URLSessionTask` which failed.
  337. /// - error: The early failure `AFError`.
  338. func didFailTask(_ task: URLSessionTask, earlyWithError error: AFError) {
  339. self.error = error
  340. // Task will still complete, so didCompleteTask(_:with:) will handle retry.
  341. eventMonitor?.request(self, didFailTask: task, earlyWithError: error)
  342. }
  343. /// Called when a `URLSessionTask` completes. All tasks will eventually call this method.
  344. ///
  345. /// - Note: Response validation is synchronously triggered in this step.
  346. ///
  347. /// - Parameters:
  348. /// - task: The `URLSessionTask` which completed.
  349. /// - error: The `AFError` `task` may have completed with. If `error` has already been set on the instance, this
  350. /// value is ignored.
  351. func didCompleteTask(_ task: URLSessionTask, with error: AFError?) {
  352. self.error = self.error ?? error
  353. protectedValidators.directValue.forEach { $0() }
  354. eventMonitor?.request(self, didCompleteTask: task, with: error)
  355. retryOrFinish(error: self.error)
  356. }
  357. /// Called when the `RequestDelegate` is going to retry this `Request`. Calls `reset()`.
  358. func prepareForRetry() {
  359. protectedMutableState.write { $0.retryCount += 1 }
  360. reset()
  361. eventMonitor?.requestIsRetrying(self)
  362. }
  363. /// Called to determine whether retry will be triggered for the particular error, or whether the instance should
  364. /// call `finish()`.
  365. ///
  366. /// - Parameter error: The possible `AFError` which may trigger retry.
  367. func retryOrFinish(error: AFError?) {
  368. guard let error = error, let delegate = delegate else { finish(); return }
  369. delegate.retryResult(for: self, dueTo: error) { retryResult in
  370. switch retryResult {
  371. case .doNotRetry:
  372. self.finish()
  373. case let .doNotRetryWithError(retryError):
  374. self.finish(error: retryError.asAFError(orFailWith: "Received retryError was not already AFError"))
  375. case .retry, .retryWithDelay:
  376. delegate.retryRequest(self, withDelay: retryResult.delay)
  377. }
  378. }
  379. }
  380. /// Finishes this `Request` and starts the response serializers.
  381. ///
  382. /// - Parameter error: The possible `Error` with which the instance will finish.
  383. func finish(error: AFError? = nil) {
  384. if let error = error { self.error = error }
  385. // Start response handlers
  386. processNextResponseSerializer()
  387. eventMonitor?.requestDidFinish(self)
  388. }
  389. /// Appends the response serialization closure to the instance.
  390. ///
  391. /// - Note: This method will also `resume` the instance if `delegate.startImmediately` returns `true`.
  392. ///
  393. /// - Parameter closure: The closure containing the response serialization call.
  394. func appendResponseSerializer(_ closure: @escaping () -> Void) {
  395. protectedMutableState.write { mutableState in
  396. mutableState.responseSerializers.append(closure)
  397. if mutableState.state == .finished {
  398. mutableState.state = .resumed
  399. }
  400. if mutableState.responseSerializerProcessingFinished {
  401. underlyingQueue.async { self.processNextResponseSerializer() }
  402. }
  403. if mutableState.state.canTransitionTo(.resumed) {
  404. underlyingQueue.async { if self.delegate?.startImmediately == true { self.resume() } }
  405. }
  406. }
  407. }
  408. /// Returns the next response serializer closure to execute if there's one left.
  409. ///
  410. /// - Returns: The next response serialization closure, if there is one.
  411. func nextResponseSerializer() -> (() -> Void)? {
  412. var responseSerializer: (() -> Void)?
  413. protectedMutableState.write { mutableState in
  414. let responseSerializerIndex = mutableState.responseSerializerCompletions.count
  415. if responseSerializerIndex < mutableState.responseSerializers.count {
  416. responseSerializer = mutableState.responseSerializers[responseSerializerIndex]
  417. }
  418. }
  419. return responseSerializer
  420. }
  421. /// Processes the next response serializer and calls all completions if response serialization is complete.
  422. func processNextResponseSerializer() {
  423. guard let responseSerializer = nextResponseSerializer() else {
  424. // Execute all response serializer completions and clear them
  425. var completions: [() -> Void] = []
  426. protectedMutableState.write { mutableState in
  427. completions = mutableState.responseSerializerCompletions
  428. // Clear out all response serializers and response serializer completions in mutable state since the
  429. // request is complete. It's important to do this prior to calling the completion closures in case
  430. // the completions call back into the request triggering a re-processing of the response serializers.
  431. // An example of how this can happen is by calling cancel inside a response completion closure.
  432. mutableState.responseSerializers.removeAll()
  433. mutableState.responseSerializerCompletions.removeAll()
  434. if mutableState.state.canTransitionTo(.finished) {
  435. mutableState.state = .finished
  436. }
  437. mutableState.responseSerializerProcessingFinished = true
  438. }
  439. completions.forEach { $0() }
  440. // Cleanup the request
  441. cleanup()
  442. return
  443. }
  444. serializationQueue.async { responseSerializer() }
  445. }
  446. /// Notifies the `Request` that the response serializer is complete.
  447. ///
  448. /// - Parameter completion: The completion handler provided with the response serializer, called when all serializers
  449. /// are complete.
  450. func responseSerializerDidComplete(completion: @escaping () -> Void) {
  451. protectedMutableState.write { $0.responseSerializerCompletions.append(completion) }
  452. processNextResponseSerializer()
  453. }
  454. /// Resets all task and response serializer related state for retry.
  455. func reset() {
  456. error = nil
  457. uploadProgress.totalUnitCount = 0
  458. uploadProgress.completedUnitCount = 0
  459. downloadProgress.totalUnitCount = 0
  460. downloadProgress.completedUnitCount = 0
  461. protectedMutableState.write { $0.responseSerializerCompletions = [] }
  462. }
  463. /// Called when updating the upload progress.
  464. ///
  465. /// - Parameters:
  466. /// - totalBytesSent: Total bytes sent so far.
  467. /// - totalBytesExpectedToSend: Total bytes expected to send.
  468. func updateUploadProgress(totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
  469. uploadProgress.totalUnitCount = totalBytesExpectedToSend
  470. uploadProgress.completedUnitCount = totalBytesSent
  471. uploadProgressHandler?.queue.async { self.uploadProgressHandler?.handler(self.uploadProgress) }
  472. }
  473. /// Perform a closure on the current `state` while locked.
  474. ///
  475. /// - Parameter perform: The closure to perform.
  476. func withState(perform: (State) -> Void) {
  477. protectedMutableState.withState(perform: perform)
  478. }
  479. // MARK: Task Creation
  480. /// Called when creating a `URLSessionTask` for this `Request`. Subclasses must override.
  481. ///
  482. /// - Parameters:
  483. /// - request: `URLRequest` to use to create the `URLSessionTask`.
  484. /// - session: `URLSession` which creates the `URLSessionTask`.
  485. ///
  486. /// - Returns: The `URLSessionTask` created.
  487. func task(for request: URLRequest, using session: URLSession) -> URLSessionTask {
  488. fatalError("Subclasses must override.")
  489. }
  490. // MARK: - Public API
  491. // These APIs are callable from any queue.
  492. // MARK: State
  493. /// Cancels the instance. Once cancelled, a `Request` can no longer be resumed or suspended.
  494. ///
  495. /// - Returns: The instance.
  496. @discardableResult
  497. public func cancel() -> Self {
  498. protectedMutableState.write { mutableState in
  499. guard mutableState.state.canTransitionTo(.cancelled) else { return }
  500. mutableState.state = .cancelled
  501. underlyingQueue.async { self.didCancel() }
  502. guard let task = mutableState.tasks.last, task.state != .completed else {
  503. underlyingQueue.async { self.finish() }
  504. return
  505. }
  506. // Resume to ensure metrics are gathered.
  507. task.resume()
  508. task.cancel()
  509. underlyingQueue.async { self.didCancelTask(task) }
  510. }
  511. return self
  512. }
  513. /// Suspends the instance.
  514. ///
  515. /// - Returns: The instance.
  516. @discardableResult
  517. public func suspend() -> Self {
  518. protectedMutableState.write { mutableState in
  519. guard mutableState.state.canTransitionTo(.suspended) else { return }
  520. mutableState.state = .suspended
  521. underlyingQueue.async { self.didSuspend() }
  522. guard let task = mutableState.tasks.last, task.state != .completed else { return }
  523. task.suspend()
  524. underlyingQueue.async { self.didSuspendTask(task) }
  525. }
  526. return self
  527. }
  528. /// Resumes the instance.
  529. ///
  530. /// - Returns: The instance.
  531. @discardableResult
  532. public func resume() -> Self {
  533. protectedMutableState.write { mutableState in
  534. guard mutableState.state.canTransitionTo(.resumed) else { return }
  535. mutableState.state = .resumed
  536. underlyingQueue.async { self.didResume() }
  537. guard let task = mutableState.tasks.last, task.state != .completed else { return }
  538. task.resume()
  539. underlyingQueue.async { self.didResumeTask(task) }
  540. }
  541. return self
  542. }
  543. // MARK: - Closure API
  544. /// Associates a credential using the provided values with the instance.
  545. ///
  546. /// - Parameters:
  547. /// - username: The username.
  548. /// - password: The password.
  549. /// - persistence: The `URLCredential.Persistence` for the created `URLCredential`. `.forSession` by default.
  550. ///
  551. /// - Returns: The instance.
  552. @discardableResult
  553. public func authenticate(username: String, password: String, persistence: URLCredential.Persistence = .forSession) -> Self {
  554. let credential = URLCredential(user: username, password: password, persistence: persistence)
  555. return authenticate(with: credential)
  556. }
  557. /// Associates the provided credential with the instance.
  558. ///
  559. /// - Parameter credential: The `URLCredential`.
  560. ///
  561. /// - Returns: The instance.
  562. @discardableResult
  563. public func authenticate(with credential: URLCredential) -> Self {
  564. protectedMutableState.write { $0.credential = credential }
  565. return self
  566. }
  567. /// Sets a closure to be called periodically during the lifecycle of the instance as data is read from the server.
  568. ///
  569. /// - Note: Only the last closure provided is used.
  570. ///
  571. /// - Parameters:
  572. /// - queue: The `DispatchQueue` to execute the closure on. `.main` by default.
  573. /// - closure: The closure to be executed periodically as data is read from the server.
  574. ///
  575. /// - Returns: The instance.
  576. @discardableResult
  577. public func downloadProgress(queue: DispatchQueue = .main, closure: @escaping ProgressHandler) -> Self {
  578. protectedMutableState.write { $0.downloadProgressHandler = (handler: closure, queue: queue) }
  579. return self
  580. }
  581. /// Sets a closure to be called periodically during the lifecycle of the instance as data is sent to the server.
  582. ///
  583. /// - Note: Only the last closure provided is used.
  584. ///
  585. /// - Parameters:
  586. /// - queue: The `DispatchQueue` to execute the closure on. `.main` by default.
  587. /// - closure: The closure to be executed periodically as data is sent to the server.
  588. ///
  589. /// - Returns: The instance.
  590. @discardableResult
  591. public func uploadProgress(queue: DispatchQueue = .main, closure: @escaping ProgressHandler) -> Self {
  592. protectedMutableState.write { $0.uploadProgressHandler = (handler: closure, queue: queue) }
  593. return self
  594. }
  595. // MARK: Redirects
  596. /// Sets the redirect handler for the instance which will be used if a redirect response is encountered.
  597. ///
  598. /// - Note: Attempting to set the redirect handler more than once is a logic error and will crash.
  599. ///
  600. /// - Parameter handler: The `RedirectHandler`.
  601. ///
  602. /// - Returns: The instance.
  603. @discardableResult
  604. public func redirect(using handler: RedirectHandler) -> Self {
  605. protectedMutableState.write { mutableState in
  606. precondition(mutableState.redirectHandler == nil, "Redirect handler has already been set.")
  607. mutableState.redirectHandler = handler
  608. }
  609. return self
  610. }
  611. // MARK: Cached Responses
  612. /// Sets the cached response handler for the `Request` which will be used when attempting to cache a response.
  613. ///
  614. /// - Note: Attempting to set the cache handler more than once is a logic error and will crash.
  615. ///
  616. /// - Parameter handler: The `CachedResponseHandler`.
  617. ///
  618. /// - Returns: The instance.
  619. @discardableResult
  620. public func cacheResponse(using handler: CachedResponseHandler) -> Self {
  621. protectedMutableState.write { mutableState in
  622. precondition(mutableState.cachedResponseHandler == nil, "Cached response handler has already been set.")
  623. mutableState.cachedResponseHandler = handler
  624. }
  625. return self
  626. }
  627. /// Sets a handler to be called when the cURL description of the request is available.
  628. ///
  629. /// - Note: When waiting for a `Request`'s `URLRequest` to be created, only the last `handler` will be called.
  630. ///
  631. /// - Parameter handler: Closure to be called when the cURL description is available.
  632. ///
  633. /// - Returns: The instance.
  634. @discardableResult
  635. public func cURLDescription(calling handler: @escaping (String) -> Void) -> Self {
  636. protectedMutableState.write { mutableState in
  637. if mutableState.requests.last != nil {
  638. underlyingQueue.async { handler(self.cURLDescription()) }
  639. } else {
  640. mutableState.cURLHandler = handler
  641. }
  642. }
  643. return self
  644. }
  645. // MARK: Cleanup
  646. /// Final cleanup step executed when the instance finishes response serialization.
  647. func cleanup() {
  648. delegate?.cleanup(after: self)
  649. // No-op: override in subclass
  650. }
  651. }
  652. // MARK: - Protocol Conformances
  653. extension Request: Equatable {
  654. public static func ==(lhs: Request, rhs: Request) -> Bool {
  655. return lhs.id == rhs.id
  656. }
  657. }
  658. extension Request: Hashable {
  659. public func hash(into hasher: inout Hasher) {
  660. hasher.combine(id)
  661. }
  662. }
  663. extension Request: CustomStringConvertible {
  664. /// A textual representation of this instance, including the `HTTPMethod` and `URL` if the `URLRequest` has been
  665. /// created, as well as the response status code, if a response has been received.
  666. public var description: String {
  667. guard let request = performedRequests.last ?? lastRequest,
  668. let url = request.url,
  669. let method = request.httpMethod else { return "No request created yet." }
  670. let requestDescription = "\(method) \(url.absoluteString)"
  671. return response.map { "\(requestDescription) (\($0.statusCode))" } ?? requestDescription
  672. }
  673. }
  674. extension Request {
  675. /// cURL representation of the instance.
  676. ///
  677. /// - Returns: The cURL equivalent of the instance.
  678. public func cURLDescription() -> String {
  679. guard
  680. let request = lastRequest,
  681. let url = request.url,
  682. let host = url.host,
  683. let method = request.httpMethod else { return "$ curl command could not be created" }
  684. var components = ["$ curl -v"]
  685. components.append("-X \(method)")
  686. if let credentialStorage = delegate?.sessionConfiguration.urlCredentialStorage {
  687. let protectionSpace = URLProtectionSpace(host: host,
  688. port: url.port ?? 0,
  689. protocol: url.scheme,
  690. realm: host,
  691. authenticationMethod: NSURLAuthenticationMethodHTTPBasic)
  692. if let credentials = credentialStorage.credentials(for: protectionSpace)?.values {
  693. for credential in credentials {
  694. guard let user = credential.user, let password = credential.password else { continue }
  695. components.append("-u \(user):\(password)")
  696. }
  697. } else {
  698. if let credential = credential, let user = credential.user, let password = credential.password {
  699. components.append("-u \(user):\(password)")
  700. }
  701. }
  702. }
  703. if let configuration = delegate?.sessionConfiguration, configuration.httpShouldSetCookies {
  704. if
  705. let cookieStorage = configuration.httpCookieStorage,
  706. let cookies = cookieStorage.cookies(for: url), !cookies.isEmpty {
  707. let allCookies = cookies.map { "\($0.name)=\($0.value)" }.joined(separator: ";")
  708. components.append("-b \"\(allCookies)\"")
  709. }
  710. }
  711. var headers = HTTPHeaders()
  712. if let sessionHeaders = delegate?.sessionConfiguration.headers {
  713. for header in sessionHeaders where header.name != "Cookie" {
  714. headers[header.name] = header.value
  715. }
  716. }
  717. for header in request.headers where header.name != "Cookie" {
  718. headers[header.name] = header.value
  719. }
  720. for header in headers {
  721. let escapedValue = header.value.replacingOccurrences(of: "\"", with: "\\\"")
  722. components.append("-H \"\(header.name): \(escapedValue)\"")
  723. }
  724. if let httpBodyData = request.httpBody {
  725. let httpBody = String(decoding: httpBodyData, as: UTF8.self)
  726. var escapedBody = httpBody.replacingOccurrences(of: "\\\"", with: "\\\\\"")
  727. escapedBody = escapedBody.replacingOccurrences(of: "\"", with: "\\\"")
  728. components.append("-d \"\(escapedBody)\"")
  729. }
  730. components.append("\"\(url.absoluteString)\"")
  731. return components.joined(separator: " \\\n\t")
  732. }
  733. }
  734. /// Protocol abstraction for `Request`'s communication back to the `SessionDelegate`.
  735. public protocol RequestDelegate: AnyObject {
  736. /// `URLSessionConfiguration` used to create the underlying `URLSessionTask`s.
  737. var sessionConfiguration: URLSessionConfiguration { get }
  738. /// Determines whether the `Request` should automatically call `resume()` when adding the first response handler.
  739. var startImmediately: Bool { get }
  740. /// Notifies the delegate the `Request` has reached a point where it needs cleanup.
  741. ///
  742. /// - Parameter request: The `Request` to cleanup after.
  743. func cleanup(after request: Request)
  744. /// Asynchronously ask the delegate whether a `Request` will be retried.
  745. ///
  746. /// - Parameters:
  747. /// - request: `Request` which failed.
  748. /// - error: `Error` which produced the failure.
  749. /// - completion: Closure taking the `RetryResult` for evaluation.
  750. func retryResult(for request: Request, dueTo error: AFError, completion: @escaping (RetryResult) -> Void)
  751. /// Asynchronously retry the `Request`.
  752. ///
  753. /// - Parameters:
  754. /// - request: `Request` which will be retried.
  755. /// - timeDelay: `TimeInterval` after which the retry will be triggered.
  756. func retryRequest(_ request: Request, withDelay timeDelay: TimeInterval?)
  757. }
  758. // MARK: - Subclasses
  759. // MARK: - DataRequest
  760. /// `Request` subclass which handles in-memory `Data` download using `URLSessionDataTask`.
  761. public class DataRequest: Request {
  762. /// `URLRequestConvertible` value used to create `URLRequest`s for this instance.
  763. public let convertible: URLRequestConvertible
  764. /// `Data` read from the server so far.
  765. public var data: Data? { return protectedData.directValue }
  766. /// Protected storage for the `Data` read by the instance.
  767. private var protectedData: Protector<Data?> = Protector(nil)
  768. /// Creates a `DataRequest` using the provided parameters.
  769. ///
  770. /// - Parameters:
  771. /// - id: `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()` by default.
  772. /// - convertible: `URLRequestConvertible` value used to create `URLRequest`s for this instance.
  773. /// - underlyingQueue: `DispatchQueue` on which all internal `Request` work is performed.
  774. /// - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default targets
  775. /// `underlyingQueue`, but can be passed another queue from a `Session`.
  776. /// - eventMonitor: `EventMonitor` called for event callbacks from internal `Request` actions.
  777. /// - interceptor: `RequestInterceptor` used throughout the request lifecycle.
  778. /// - delegate: `RequestDelegate` that provides an interface to actions not performed by the `Request`.
  779. init(id: UUID = UUID(),
  780. convertible: URLRequestConvertible,
  781. underlyingQueue: DispatchQueue,
  782. serializationQueue: DispatchQueue,
  783. eventMonitor: EventMonitor?,
  784. interceptor: RequestInterceptor?,
  785. delegate: RequestDelegate) {
  786. self.convertible = convertible
  787. super.init(id: id,
  788. underlyingQueue: underlyingQueue,
  789. serializationQueue: serializationQueue,
  790. eventMonitor: eventMonitor,
  791. interceptor: interceptor,
  792. delegate: delegate)
  793. }
  794. override func reset() {
  795. super.reset()
  796. protectedData.directValue = nil
  797. }
  798. /// Called when `Data` is received by this instance.
  799. ///
  800. /// - Note: Also calls `updateDownloadProgress`.
  801. ///
  802. /// - Parameter data: The `Data` received.
  803. func didReceive(data: Data) {
  804. if self.data == nil {
  805. protectedData.directValue = data
  806. } else {
  807. protectedData.append(data)
  808. }
  809. updateDownloadProgress()
  810. }
  811. override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask {
  812. let copiedRequest = request
  813. return session.dataTask(with: copiedRequest)
  814. }
  815. /// Called to updated the `downloadProgress` of the instance.
  816. func updateDownloadProgress() {
  817. let totalBytesReceived = Int64(data?.count ?? 0)
  818. let totalBytesExpected = task?.response?.expectedContentLength ?? NSURLSessionTransferSizeUnknown
  819. downloadProgress.totalUnitCount = totalBytesExpected
  820. downloadProgress.completedUnitCount = totalBytesReceived
  821. downloadProgressHandler?.queue.async { self.downloadProgressHandler?.handler(self.downloadProgress) }
  822. }
  823. /// Validates the request, using the specified closure.
  824. ///
  825. /// - Note: If validation fails, subsequent calls to response handlers will have an associated error.
  826. ///
  827. /// - Parameter validation: `Validation` closure used to validate the response.
  828. ///
  829. /// - Returns: The instance.
  830. @discardableResult
  831. public func validate(_ validation: @escaping Validation) -> Self {
  832. let validator: () -> Void = { [unowned self] in
  833. guard self.error == nil, let response = self.response else { return }
  834. let result = validation(self.request, response, self.data)
  835. if case let .failure(error) = result { self.error = error.asAFError(or: .responseValidationFailed(reason: .customValidationFailed(error: error))) }
  836. self.eventMonitor?.request(self,
  837. didValidateRequest: self.request,
  838. response: response,
  839. data: self.data,
  840. withResult: result)
  841. }
  842. protectedValidators.append(validator)
  843. return self
  844. }
  845. }
  846. // MARK: - DownloadRequest
  847. /// `Request` subclass which downloads `Data` to a file on disk using `URLSessionDownloadTask`.
  848. public class DownloadRequest: Request {
  849. /// A set of options to be executed prior to moving a downloaded file from the temporary `URL` to the destination
  850. /// `URL`.
  851. public struct Options: OptionSet {
  852. /// Specifies that intermediate directories for the destination URL should be created.
  853. public static let createIntermediateDirectories = Options(rawValue: 1 << 0)
  854. /// Specifies that any previous file at the destination `URL` should be removed.
  855. public static let removePreviousFile = Options(rawValue: 1 << 1)
  856. /// Returns the raw bitmask value of the option and satisfies the `RawRepresentable` protocol.
  857. public let rawValue: Int
  858. public init(rawValue: Int) {
  859. self.rawValue = rawValue
  860. }
  861. }
  862. // MARK: Destination
  863. /// A closure executed once a download request has successfully completed in order to determine where to move the
  864. /// temporary file written to during the download process. The closure takes two arguments: the temporary file URL
  865. /// and the URL response, and returns a two arguments: the file URL where the temporary file should be moved and
  866. /// the options defining how the file should be moved.
  867. public typealias Destination = (_ temporaryURL: URL,
  868. _ response: HTTPURLResponse) -> (destinationURL: URL, options: Options)
  869. // MARK: Destination
  870. /// Creates a download file destination closure which uses the default file manager to move the temporary file to a
  871. /// file URL in the first available directory with the specified search path directory and search path domain mask.
  872. ///
  873. /// - Parameters:
  874. /// - directory: The search path directory. `.documentDirectory` by default.
  875. /// - domain: The search path domain mask. `.userDomainMask` by default.
  876. /// - options: `DownloadRequest.Options` used when moving the downloaded file to its destination. None by
  877. /// default.
  878. /// - Returns: The `Destination` closure.
  879. public class func suggestedDownloadDestination(for directory: FileManager.SearchPathDirectory = .documentDirectory,
  880. in domain: FileManager.SearchPathDomainMask = .userDomainMask,
  881. options: Options = []) -> Destination {
  882. return { temporaryURL, response in
  883. let directoryURLs = FileManager.default.urls(for: directory, in: domain)
  884. let url = directoryURLs.first?.appendingPathComponent(response.suggestedFilename!) ?? temporaryURL
  885. return (url, options)
  886. }
  887. }
  888. /// Default `Destination` used by Alamofire to ensure all downloads persist. This `Destination` prepends
  889. /// `Alamofire_` to the automatically generated download name and moves it within the temporary directory. Files
  890. /// with this destination must be additionally moved if they should survive the system reclamation of temporary
  891. /// space.
  892. static let defaultDestination: Destination = { url, _ in
  893. let filename = "Alamofire_\(url.lastPathComponent)"
  894. let destination = url.deletingLastPathComponent().appendingPathComponent(filename)
  895. return (destination, [])
  896. }
  897. /// Type describing the source used to create the underlying `URLSessionDownloadTask`.
  898. public enum Downloadable {
  899. /// Download should be started from the `URLRequest` produced by the associated `URLRequestConvertible` value.
  900. case request(URLRequestConvertible)
  901. /// Download should be started from the associated resume `Data` value.
  902. case resumeData(Data)
  903. }
  904. // MARK: Mutable State
  905. /// Type containing all mutable state for `DownloadRequest` instances.
  906. private struct DownloadRequestMutableState {
  907. /// Possible resume `Data` produced when cancelling the instance.
  908. var resumeData: Data?
  909. /// `URL` to which `Data` is being downloaded.
  910. var fileURL: URL?
  911. }
  912. /// Protected mutable state specific to `DownloadRequest`.
  913. private let protectedDownloadMutableState: Protector<DownloadRequestMutableState> = Protector(DownloadRequestMutableState())
  914. /// If the download is resumable and eventually cancelled, this value may be used to resume the download using the
  915. /// `download(resumingWith data:)` API.
  916. ///
  917. /// - Note: For more information about `resumeData`, see [Apple's documentation](https://developer.apple.com/documentation/foundation/urlsessiondownloadtask/1411634-cancel).
  918. public var resumeData: Data? { return protectedDownloadMutableState.directValue.resumeData }
  919. /// If the download is successful, the `URL` where the file was downloaded.
  920. public var fileURL: URL? { return protectedDownloadMutableState.directValue.fileURL }
  921. // MARK: Initial State
  922. /// `Downloadable` value used for this instance.
  923. public let downloadable: Downloadable
  924. /// The `Destination` to which the downloaded file is moved.
  925. let destination: Destination
  926. /// Creates a `DownloadRequest` using the provided parameters.
  927. ///
  928. /// - Parameters:
  929. /// - id: `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()` by default.
  930. /// - downloadable: `Downloadable` value used to create `URLSessionDownloadTasks` for the instance.
  931. /// - underlyingQueue: `DispatchQueue` on which all internal `Request` work is performed.
  932. /// - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default targets
  933. /// `underlyingQueue`, but can be passed another queue from a `Session`.
  934. /// - eventMonitor: `EventMonitor` called for event callbacks from internal `Request` actions.
  935. /// - interceptor: `RequestInterceptor` used throughout the request lifecycle.
  936. /// - delegate: `RequestDelegate` that provides an interface to actions not performed by the `Request`
  937. /// - destination: `Destination` closure used to move the downloaded file to its final location.
  938. init(id: UUID = UUID(),
  939. downloadable: Downloadable,
  940. underlyingQueue: DispatchQueue,
  941. serializationQueue: DispatchQueue,
  942. eventMonitor: EventMonitor?,
  943. interceptor: RequestInterceptor?,
  944. delegate: RequestDelegate,
  945. destination: @escaping Destination) {
  946. self.downloadable = downloadable
  947. self.destination = destination
  948. super.init(id: id,
  949. underlyingQueue: underlyingQueue,
  950. serializationQueue: serializationQueue,
  951. eventMonitor: eventMonitor,
  952. interceptor: interceptor,
  953. delegate: delegate)
  954. }
  955. override func reset() {
  956. super.reset()
  957. protectedDownloadMutableState.write {
  958. $0.resumeData = nil
  959. $0.fileURL = nil
  960. }
  961. }
  962. /// Called when a download has finished.
  963. ///
  964. /// - Parameters:
  965. /// - task: `URLSessionTask` that finished the download.
  966. /// - result: `Result` of the automatic move to `destination`.
  967. func didFinishDownloading(using task: URLSessionTask, with result: Result<URL, AFError>) {
  968. eventMonitor?.request(self, didFinishDownloadingUsing: task, with: result)
  969. switch result {
  970. case let .success(url): protectedDownloadMutableState.write { $0.fileURL = url }
  971. case let .failure(error): self.error = error
  972. }
  973. }
  974. /// Updates the `downloadProgress` using the provided values.
  975. ///
  976. /// - Parameters:
  977. /// - bytesWritten: Total bytes written so far.
  978. /// - totalBytesExpectedToWrite: Total bytes expected to write.
  979. func updateDownloadProgress(bytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
  980. downloadProgress.totalUnitCount = totalBytesExpectedToWrite
  981. downloadProgress.completedUnitCount += bytesWritten
  982. downloadProgressHandler?.queue.async { self.downloadProgressHandler?.handler(self.downloadProgress) }
  983. }
  984. override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask {
  985. return session.downloadTask(with: request)
  986. }
  987. /// Creates a `URLSessionTask` from the provided resume data.
  988. ///
  989. /// - Parameters:
  990. /// - data: `Data` used to resume the download.
  991. /// - session: `URLSession` used to create the `URLSessionTask`.
  992. ///
  993. /// - Returns: The `URLSessionTask` created.
  994. public func task(forResumeData data: Data, using session: URLSession) -> URLSessionTask {
  995. return session.downloadTask(withResumeData: data)
  996. }
  997. /// Cancels the instance. Once cancelled, a `DownloadRequest` can no longer be resumed or suspended.
  998. ///
  999. /// - Note: This method will NOT produce resume data. If you wish to cancel and produce resume data, use
  1000. /// `cancel(producingResumeData:)` or `cancel(byProducingResumeData:)`.
  1001. ///
  1002. /// - Returns: The instance.
  1003. @discardableResult
  1004. public override func cancel() -> Self {
  1005. return cancel(producingResumeData: false)
  1006. }
  1007. /// Cancels the instance, optionally producing resume data. Once cancelled, a `DownloadRequest` can no longer be
  1008. /// resumed or suspended.
  1009. ///
  1010. /// - Note: If `producingResumeData` is `true`, the `resumeData` property will be populated with any resume data, if
  1011. /// available.
  1012. ///
  1013. /// - Returns: The instance.
  1014. @discardableResult
  1015. public func cancel(producingResumeData shouldProduceResumeData: Bool) -> Self {
  1016. return cancel(optionallyProducingResumeData: shouldProduceResumeData ? { _ in } : nil)
  1017. }
  1018. /// Cancels the instance while producing resume data. Once cancelled, a `DownloadRequest` can no longer be resumed
  1019. /// or suspended.
  1020. ///
  1021. /// - Note: The resume data passed to the completion handler will also be available on the instance's `resumeData`
  1022. /// property.
  1023. ///
  1024. /// - Parameter completionHandler: The completion handler that is called when the download has been successfully
  1025. /// cancelled. It is not guaranteed to be called on a particular queue, so you may
  1026. /// want use an appropriate queue to perform your work.
  1027. ///
  1028. /// - Returns: The instance.
  1029. @discardableResult
  1030. public func cancel(byProducingResumeData completionHandler: @escaping (_ data: Data?) -> Void) -> Self {
  1031. return cancel(optionallyProducingResumeData: completionHandler)
  1032. }
  1033. /// Internal implementation of cancellation that optionally takes a resume data handler. If no handler is passed,
  1034. /// cancellation is performed without producing resume data.
  1035. ///
  1036. /// - Parameter completionHandler: Optional resume data handler.
  1037. ///
  1038. /// - Returns: The instance.
  1039. private func cancel(optionallyProducingResumeData completionHandler: ((_ resumeData: Data?) -> Void)?) -> Self {
  1040. protectedMutableState.write { mutableState in
  1041. guard mutableState.state.canTransitionTo(.cancelled) else { return }
  1042. mutableState.state = .cancelled
  1043. underlyingQueue.async { self.didCancel() }
  1044. guard let task = mutableState.tasks.last as? URLSessionDownloadTask, task.state != .completed else {
  1045. underlyingQueue.async { self.finish() }
  1046. return
  1047. }
  1048. if let completionHandler = completionHandler {
  1049. // Resume to ensure metrics are gathered.
  1050. task.resume()
  1051. task.cancel { resumeData in
  1052. self.protectedDownloadMutableState.write { $0.resumeData = resumeData }
  1053. self.underlyingQueue.async { self.didCancelTask(task) }
  1054. completionHandler(resumeData)
  1055. }
  1056. } else {
  1057. // Resume to ensure metrics are gathered.
  1058. task.resume()
  1059. task.cancel()
  1060. self.underlyingQueue.async { self.didCancelTask(task) }
  1061. }
  1062. }
  1063. return self
  1064. }
  1065. /// Validates the request, using the specified closure.
  1066. ///
  1067. /// - Note: If validation fails, subsequent calls to response handlers will have an associated error.
  1068. ///
  1069. /// - Parameter validation: `Validation` closure to validate the response.
  1070. ///
  1071. /// - Returns: The instance.
  1072. @discardableResult
  1073. public func validate(_ validation: @escaping Validation) -> Self {
  1074. let validator: () -> Void = { [unowned self] in
  1075. guard self.error == nil, let response = self.response else { return }
  1076. let result = validation(self.request, response, self.fileURL)
  1077. if case let .failure(error) = result { self.error = error.asAFError(or: .responseValidationFailed(reason: .customValidationFailed(error: error))) }
  1078. self.eventMonitor?.request(self,
  1079. didValidateRequest: self.request,
  1080. response: response,
  1081. fileURL: self.fileURL,
  1082. withResult: result)
  1083. }
  1084. protectedValidators.append(validator)
  1085. return self
  1086. }
  1087. }
  1088. // MARK: - UploadRequest
  1089. /// `DataRequest` subclass which handles `Data` upload from memory, file, or stream using `URLSessionUploadTask`.
  1090. public class UploadRequest: DataRequest {
  1091. /// Type describing the origin of the upload, whether `Data`, file, or stream.
  1092. public enum Uploadable {
  1093. /// Upload from the provided `Data` value.
  1094. case data(Data)
  1095. /// Upload from the provided file `URL`, as well as a `Bool` determining whether the source file should be
  1096. /// automatically removed once uploaded.
  1097. case file(URL, shouldRemove: Bool)
  1098. /// Upload from the provided `InputStream`.
  1099. case stream(InputStream)
  1100. }
  1101. // MARK: Initial State
  1102. /// The `UploadableConvertible` value used to produce the `Uploadable` value for this instance.
  1103. public let upload: UploadableConvertible
  1104. /// `FileManager` used to perform cleanup tasks, including the removal of multipart form encoded payloads written
  1105. /// to disk.
  1106. public let fileManager: FileManager
  1107. // MARK: Mutable State
  1108. /// `Uploadable` value used by the instance.
  1109. public var uploadable: Uploadable?
  1110. /// Creates an `UploadRequest` using the provided parameters.
  1111. ///
  1112. /// - Parameters:
  1113. /// - id: `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()` by default.
  1114. /// - convertible: `UploadConvertible` value used to determine the type of upload to be performed.
  1115. /// - underlyingQueue: `DispatchQueue` on which all internal `Request` work is performed.
  1116. /// - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default targets
  1117. /// `underlyingQueue`, but can be passed another queue from a `Session`.
  1118. /// - eventMonitor: `EventMonitor` called for event callbacks from internal `Request` actions.
  1119. /// - interceptor: `RequestInterceptor` used throughout the request lifecycle.
  1120. /// - delegate: `RequestDelegate` that provides an interface to actions not performed by the `Request`.
  1121. init(id: UUID = UUID(),
  1122. convertible: UploadConvertible,
  1123. underlyingQueue: DispatchQueue,
  1124. serializationQueue: DispatchQueue,
  1125. eventMonitor: EventMonitor?,
  1126. interceptor: RequestInterceptor?,
  1127. fileManager: FileManager,
  1128. delegate: RequestDelegate) {
  1129. upload = convertible
  1130. self.fileManager = fileManager
  1131. super.init(id: id,
  1132. convertible: convertible,
  1133. underlyingQueue: underlyingQueue,
  1134. serializationQueue: serializationQueue,
  1135. eventMonitor: eventMonitor,
  1136. interceptor: interceptor,
  1137. delegate: delegate)
  1138. }
  1139. /// Called when the `Uploadable` value has been created from the `UploadConvertible`.
  1140. ///
  1141. /// - Parameter uploadable: The `Uploadable` that was created.
  1142. func didCreateUploadable(_ uploadable: Uploadable) {
  1143. self.uploadable = uploadable
  1144. eventMonitor?.request(self, didCreateUploadable: uploadable)
  1145. }
  1146. /// Called when the `Uploadable` value could not be created.
  1147. ///
  1148. /// - Parameter error: `AFError` produced by the failure.
  1149. func didFailToCreateUploadable(with error: AFError) {
  1150. self.error = error
  1151. eventMonitor?.request(self, didFailToCreateUploadableWithError: error)
  1152. retryOrFinish(error: error)
  1153. }
  1154. override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask {
  1155. guard let uploadable = uploadable else {
  1156. fatalError("Attempting to create a URLSessionUploadTask when Uploadable value doesn't exist.")
  1157. }
  1158. switch uploadable {
  1159. case let .data(data): return session.uploadTask(with: request, from: data)
  1160. case let .file(url, _): return session.uploadTask(with: request, fromFile: url)
  1161. case .stream: return session.uploadTask(withStreamedRequest: request)
  1162. }
  1163. }
  1164. /// Produces the `InputStream` from `uploadable`, if it can.
  1165. ///
  1166. /// - Note: Calling this method with a non-`.stream` `Uploadable` is a logic error and will crash.
  1167. ///
  1168. /// - Returns: The `InputStream`.
  1169. func inputStream() -> InputStream {
  1170. guard let uploadable = uploadable else {
  1171. fatalError("Attempting to access the input stream but the uploadable doesn't exist.")
  1172. }
  1173. guard case let .stream(stream) = uploadable else {
  1174. fatalError("Attempted to access the stream of an UploadRequest that wasn't created with one.")
  1175. }
  1176. eventMonitor?.request(self, didProvideInputStream: stream)
  1177. return stream
  1178. }
  1179. public override func cleanup() {
  1180. defer { super.cleanup() }
  1181. guard
  1182. let uploadable = self.uploadable,
  1183. case let .file(url, shouldRemove) = uploadable,
  1184. shouldRemove
  1185. else { return }
  1186. try? fileManager.removeItem(at: url)
  1187. }
  1188. }
  1189. /// A type that can produce an `UploadRequest.Uploadable` value.
  1190. public protocol UploadableConvertible {
  1191. /// Produces an `UploadRequest.Uploadable` value from the instance.
  1192. ///
  1193. /// - Returns: The `UploadRequest.Uploadable`.
  1194. /// - Throws: Any `Error` produced during creation.
  1195. func createUploadable() throws -> UploadRequest.Uploadable
  1196. }
  1197. extension UploadRequest.Uploadable: UploadableConvertible {
  1198. public func createUploadable() throws -> UploadRequest.Uploadable {
  1199. return self
  1200. }
  1201. }
  1202. /// A type that can be converted to an upload, whether from an `UploadRequest.Uploadable` or `URLRequestConvertible`.
  1203. public protocol UploadConvertible: UploadableConvertible & URLRequestConvertible {}