Request.swift 60 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454
  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` prividing 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 threadsafe 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. fileprivate(set) public 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 a 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 .doNotRetryWithError(let 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. /// - Parameter closure: The closure containing the response serialization call.
  392. func appendResponseSerializer(_ closure: @escaping () -> Void) {
  393. protectedMutableState.write { mutableState in
  394. mutableState.responseSerializers.append(closure)
  395. if mutableState.state == .finished {
  396. mutableState.state = .resumed
  397. }
  398. if mutableState.responseSerializerProcessingFinished {
  399. underlyingQueue.async { self.processNextResponseSerializer() }
  400. }
  401. }
  402. }
  403. /// Returns the next response serializer closure to execute if there's one left.
  404. ///
  405. /// - Returns: The next response serialization closure, if there is one.
  406. func nextResponseSerializer() -> (() -> Void)? {
  407. var responseSerializer: (() -> Void)?
  408. protectedMutableState.write { mutableState in
  409. let responseSerializerIndex = mutableState.responseSerializerCompletions.count
  410. if responseSerializerIndex < mutableState.responseSerializers.count {
  411. responseSerializer = mutableState.responseSerializers[responseSerializerIndex]
  412. }
  413. }
  414. return responseSerializer
  415. }
  416. /// Processes the next response serializer and calls all completions if response serialization is complete.
  417. func processNextResponseSerializer() {
  418. guard let responseSerializer = nextResponseSerializer() else {
  419. // Execute all response serializer completions and clear them
  420. var completions: [() -> Void] = []
  421. protectedMutableState.write { mutableState in
  422. completions = mutableState.responseSerializerCompletions
  423. // Clear out all response serializers and response serializer completions in mutable state since the
  424. // request is complete. It's important to do this prior to calling the completion closures in case
  425. // the completions call back into the request triggering a re-processing of the response serializers.
  426. // An example of how this can happen is by calling cancel inside a response completion closure.
  427. mutableState.responseSerializers.removeAll()
  428. mutableState.responseSerializerCompletions.removeAll()
  429. if mutableState.state.canTransitionTo(.finished) {
  430. mutableState.state = .finished
  431. }
  432. mutableState.responseSerializerProcessingFinished = true
  433. }
  434. completions.forEach { $0() }
  435. // Cleanup the request
  436. cleanup()
  437. return
  438. }
  439. serializationQueue.async { responseSerializer() }
  440. }
  441. /// Notifies the `Request` that the response serializer is complete.
  442. ///
  443. /// - Parameter completion: The completion handler provided with the response serilizer, called when all serializers
  444. /// are complete.
  445. func responseSerializerDidComplete(completion: @escaping () -> Void) {
  446. protectedMutableState.write { $0.responseSerializerCompletions.append(completion) }
  447. processNextResponseSerializer()
  448. }
  449. /// Resets all task and response serializer related state for retry.
  450. func reset() {
  451. error = nil
  452. uploadProgress.totalUnitCount = 0
  453. uploadProgress.completedUnitCount = 0
  454. downloadProgress.totalUnitCount = 0
  455. downloadProgress.completedUnitCount = 0
  456. protectedMutableState.write { $0.responseSerializerCompletions = [] }
  457. }
  458. /// Called when updating the upload progress.
  459. ///
  460. /// - Parameters:
  461. /// - totalBytesSent: Total bytes sent so far.
  462. /// - totalBytesExpectedToSend: Total bytes expected to send.
  463. func updateUploadProgress(totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
  464. uploadProgress.totalUnitCount = totalBytesExpectedToSend
  465. uploadProgress.completedUnitCount = totalBytesSent
  466. uploadProgressHandler?.queue.async { self.uploadProgressHandler?.handler(self.uploadProgress) }
  467. }
  468. /// Perform a closure on the current `state` while locked.
  469. ///
  470. /// - Parameter perform: The closure to perform.
  471. func withState(perform: (State) -> Void) {
  472. protectedMutableState.withState(perform: perform)
  473. }
  474. // MARK: Task Creation
  475. /// Called when creating a `URLSessionTask` for this `Request`. Subclasses must override.
  476. ///
  477. /// - Parameters:
  478. /// - request: `URLRequest` to use to create the `URLSessionTask`.
  479. /// - session: `URLSession` which creates the `URLSessionTask`.
  480. ///
  481. /// - Returns: The `URLSessionTask` created.
  482. func task(for request: URLRequest, using session: URLSession) -> URLSessionTask {
  483. fatalError("Subclasses must override.")
  484. }
  485. // MARK: - Public API
  486. // These APIs are callable from any queue.
  487. // MARK: State
  488. /// Cancels the instance. Once cancelled, a `Request` can no longer be resumed or suspended.
  489. ///
  490. /// - Returns: The instance.
  491. @discardableResult
  492. public func cancel() -> Self {
  493. protectedMutableState.write { (mutableState) in
  494. guard mutableState.state.canTransitionTo(.cancelled) else { return }
  495. mutableState.state = .cancelled
  496. underlyingQueue.async { self.didCancel() }
  497. guard let task = mutableState.tasks.last, task.state != .completed else {
  498. underlyingQueue.async { self.finish() }
  499. return
  500. }
  501. // Resume to ensure metrics are gathered.
  502. task.resume()
  503. task.cancel()
  504. underlyingQueue.async { self.didCancelTask(task) }
  505. }
  506. return self
  507. }
  508. /// Suspends the instance.
  509. ///
  510. /// - Returns: The instance.
  511. @discardableResult
  512. public func suspend() -> Self {
  513. protectedMutableState.write { (mutableState) in
  514. guard mutableState.state.canTransitionTo(.suspended) else { return }
  515. mutableState.state = .suspended
  516. underlyingQueue.async { self.didSuspend() }
  517. guard let task = mutableState.tasks.last, task.state != .completed else { return }
  518. task.suspend()
  519. underlyingQueue.async { self.didSuspendTask(task) }
  520. }
  521. return self
  522. }
  523. /// Resumes the instance.
  524. ///
  525. /// - Returns: The instance.
  526. @discardableResult
  527. public func resume() -> Self {
  528. protectedMutableState.write { (mutableState) in
  529. guard mutableState.state.canTransitionTo(.resumed) else { return }
  530. mutableState.state = .resumed
  531. underlyingQueue.async { self.didResume() }
  532. guard let task = mutableState.tasks.last, task.state != .completed else { return }
  533. task.resume()
  534. underlyingQueue.async { self.didResumeTask(task) }
  535. }
  536. return self
  537. }
  538. // MARK: - Closure API
  539. /// Associates a credential using the provided values with the instance.
  540. ///
  541. /// - Parameters:
  542. /// - username: The username.
  543. /// - password: The password.
  544. /// - persistence: The `URLCredential.Persistence` for the created `URLCredential`. `.forSession` by default.
  545. ///
  546. /// - Returns: The instance.
  547. @discardableResult
  548. public func authenticate(username: String, password: String, persistence: URLCredential.Persistence = .forSession) -> Self {
  549. let credential = URLCredential(user: username, password: password, persistence: persistence)
  550. return authenticate(with: credential)
  551. }
  552. /// Associates the provided credential with the instance.
  553. ///
  554. /// - Parameter credential: The `URLCredential`.
  555. ///
  556. /// - Returns: The instance.
  557. @discardableResult
  558. public func authenticate(with credential: URLCredential) -> Self {
  559. protectedMutableState.write { $0.credential = credential }
  560. return self
  561. }
  562. /// Sets a closure to be called periodically during the lifecycle of the instance as data is read from the server.
  563. ///
  564. /// - Note: Only the last closure provided is used.
  565. ///
  566. /// - Parameters:
  567. /// - queue: The `DispatchQueue` to execute the closure on. `.main` by default.
  568. /// - closure: The closure to be executed periodically as data is read from the server.
  569. ///
  570. /// - Returns: The instance.
  571. @discardableResult
  572. public func downloadProgress(queue: DispatchQueue = .main, closure: @escaping ProgressHandler) -> Self {
  573. protectedMutableState.write { $0.downloadProgressHandler = (handler: closure, queue: queue) }
  574. return self
  575. }
  576. /// Sets a closure to be called periodically during the lifecycle of the instance as data is sent to the server.
  577. ///
  578. /// - Note: Only the last closure provided is used.
  579. ///
  580. /// - Parameters:
  581. /// - queue: The `DispatchQueue` to execute the closure on. `.main` by default.
  582. /// - closure: The closure to be executed periodically as data is sent to the server.
  583. ///
  584. /// - Returns: The instance.
  585. @discardableResult
  586. public func uploadProgress(queue: DispatchQueue = .main, closure: @escaping ProgressHandler) -> Self {
  587. protectedMutableState.write { $0.uploadProgressHandler = (handler: closure, queue: queue) }
  588. return self
  589. }
  590. // MARK: Redirects
  591. /// Sets the redirect handler for the instance which will be used if a redirect response is encountered.
  592. ///
  593. /// - Note: Attempting to set the redirect handler more than once is a logic error and will crash.
  594. ///
  595. /// - Parameter handler: The `RedirectHandler`.
  596. ///
  597. /// - Returns: The instance.
  598. @discardableResult
  599. public func redirect(using handler: RedirectHandler) -> Self {
  600. protectedMutableState.write { mutableState in
  601. precondition(mutableState.redirectHandler == nil, "Redirect handler has already been set.")
  602. mutableState.redirectHandler = handler
  603. }
  604. return self
  605. }
  606. // MARK: Cached Responses
  607. /// Sets the cached response handler for the `Request` which will be used when attempting to cache a response.
  608. ///
  609. /// - Note: Attempting to set the cache handler more than once is a logic error and will crash.
  610. ///
  611. /// - Parameter handler: The `CachedResponseHandler`.
  612. ///
  613. /// - Returns: The instance.
  614. @discardableResult
  615. public func cacheResponse(using handler: CachedResponseHandler) -> Self {
  616. protectedMutableState.write { mutableState in
  617. precondition(mutableState.cachedResponseHandler == nil, "Cached response handler has already been set.")
  618. mutableState.cachedResponseHandler = handler
  619. }
  620. return self
  621. }
  622. /// Sets a handler to be called when the cURL description of the request is available.
  623. ///
  624. /// - Note: When waiting for a `Request`'s `URLRequest` to be created, only the last `handler` will be called.
  625. ///
  626. /// - Parameter handler: Closure to be called when the cURL description is available.
  627. ///
  628. /// - Returns: The instance.
  629. @discardableResult
  630. public func cURLDescription(calling handler: @escaping (String) -> Void) -> Self {
  631. protectedMutableState.write { mutableState in
  632. if mutableState.requests.last != nil {
  633. underlyingQueue.async { handler(self.cURLDescription()) }
  634. } else {
  635. mutableState.cURLHandler = handler
  636. }
  637. }
  638. return self
  639. }
  640. // MARK: Cleanup
  641. /// Final cleanup step executed when the instance finishes response serialization.
  642. func cleanup() {
  643. delegate?.cleanup(after: self)
  644. // No-op: override in subclass
  645. }
  646. }
  647. // MARK: - Protocol Conformances
  648. extension Request: Equatable {
  649. public static func == (lhs: Request, rhs: Request) -> Bool {
  650. return lhs.id == rhs.id
  651. }
  652. }
  653. extension Request: Hashable {
  654. public func hash(into hasher: inout Hasher) {
  655. hasher.combine(id)
  656. }
  657. }
  658. extension Request: CustomStringConvertible {
  659. /// A textual representation of this instance, including the `HTTPMethod` and `URL` if the `URLRequest` has been
  660. /// created, as well as the response status code, if a response has been received.
  661. public var description: String {
  662. guard let request = performedRequests.last ?? lastRequest,
  663. let url = request.url,
  664. let method = request.httpMethod else { return "No request created yet." }
  665. let requestDescription = "\(method) \(url.absoluteString)"
  666. return response.map { "\(requestDescription) (\($0.statusCode))" } ?? requestDescription
  667. }
  668. }
  669. extension Request {
  670. /// cURL representation of the instance.
  671. ///
  672. /// - Returns: The cURL equivalent of the instance.
  673. public func cURLDescription() -> String {
  674. guard
  675. let request = lastRequest,
  676. let url = request.url,
  677. let host = url.host,
  678. let method = request.httpMethod else { return "$ curl command could not be created" }
  679. var components = ["$ curl -v"]
  680. components.append("-X \(method)")
  681. if let credentialStorage = delegate?.sessionConfiguration.urlCredentialStorage {
  682. let protectionSpace = URLProtectionSpace(
  683. host: host,
  684. port: url.port ?? 0,
  685. protocol: url.scheme,
  686. realm: host,
  687. authenticationMethod: NSURLAuthenticationMethodHTTPBasic
  688. )
  689. if let credentials = credentialStorage.credentials(for: protectionSpace)?.values {
  690. for credential in credentials {
  691. guard let user = credential.user, let password = credential.password else { continue }
  692. components.append("-u \(user):\(password)")
  693. }
  694. } else {
  695. if let credential = credential, let user = credential.user, let password = credential.password {
  696. components.append("-u \(user):\(password)")
  697. }
  698. }
  699. }
  700. if let configuration = delegate?.sessionConfiguration, configuration.httpShouldSetCookies {
  701. if
  702. let cookieStorage = configuration.httpCookieStorage,
  703. let cookies = cookieStorage.cookies(for: url), !cookies.isEmpty
  704. {
  705. let allCookies = cookies.map { "\($0.name)=\($0.value)" }.joined(separator: ";")
  706. components.append("-b \"\(allCookies)\"")
  707. }
  708. }
  709. var headers: [String: String] = [:]
  710. if let additionalHeaders = delegate?.sessionConfiguration.httpAdditionalHeaders as? [String: String] {
  711. for (field, value) in additionalHeaders where field != "Cookie" {
  712. headers[field] = value
  713. }
  714. }
  715. if let headerFields = request.allHTTPHeaderFields {
  716. for (field, value) in headerFields where field != "Cookie" {
  717. headers[field] = value
  718. }
  719. }
  720. for (field, value) in headers {
  721. let escapedValue = value.replacingOccurrences(of: "\"", with: "\\\"")
  722. components.append("-H \"\(field): \(escapedValue)\"")
  723. }
  724. if let httpBodyData = request.httpBody, let httpBody = String(data: httpBodyData, encoding: .utf8) {
  725. var escapedBody = httpBody.replacingOccurrences(of: "\\\"", with: "\\\\\"")
  726. escapedBody = escapedBody.replacingOccurrences(of: "\"", with: "\\\"")
  727. components.append("-d \"\(escapedBody)\"")
  728. }
  729. components.append("\"\(url.absoluteString)\"")
  730. return components.joined(separator: " \\\n\t")
  731. }
  732. }
  733. /// Protocol abstraction for `Request`'s communication back to the `SessionDelegate`.
  734. public protocol RequestDelegate: AnyObject {
  735. /// `URLSessionConfiguration` used to create the underlying `URLSessionTask`s.
  736. var sessionConfiguration: URLSessionConfiguration { get }
  737. /// Notifies the delegate the `Request` has reached a point where it needs cleanup.
  738. ///
  739. /// - Parameter request: The `Request` to cleanup after.
  740. func cleanup(after request: Request)
  741. /// Asynchronously ask the delegate whether a `Request` will be retried.
  742. ///
  743. /// - Parameters:
  744. /// - request: `Request` which failed.
  745. /// - error: `Error` which produced the failure.
  746. /// - completion: Closure taking the `RetryResult` for evaluation.
  747. func retryResult(for request: Request, dueTo error: AFError, completion: @escaping (RetryResult) -> Void)
  748. /// Asynchronously retry the `Request`.
  749. ///
  750. /// - Parameters:
  751. /// - request: `Request` which will be retried.
  752. /// - timeDelay: `TimeInterval` after which the retry will be triggered.
  753. func retryRequest(_ request: Request, withDelay timeDelay: TimeInterval?)
  754. }
  755. // MARK: - Subclasses
  756. // MARK: - DataRequest
  757. /// `Request` subclass which handles in-memory `Data` download using `URLSessionDataTask`.
  758. public class DataRequest: Request {
  759. /// `URLRequestConvertible` value used to create `URLRequest`s for this instance.
  760. public let convertible: URLRequestConvertible
  761. /// `Data` read from the server so far.
  762. public var data: Data? { return protectedData.directValue }
  763. /// Protected storage for the `Data` read by the instance.
  764. private var protectedData: Protector<Data?> = Protector(nil)
  765. /// Creates a `DataRequest` using the provided parameters.
  766. ///
  767. /// - Parameters:
  768. /// - id: `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()` by default.
  769. /// - convertible: `URLRequestConvertible` value used to create `URLRequest`s for this instance.
  770. /// - underlyingQueue: `DispatchQueue` on which all internal `Request` work is performed.
  771. /// - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default targets
  772. /// `underlyingQueue`, but can be passed another queue from a `Session`.
  773. /// - eventMonitor: `EventMonitor` called for event callbacks from internal `Request` actions.
  774. /// - interceptor: `RequestInterceptor` used throughout the request lifecycle.
  775. /// - delegate: `RequestDelegate` that provides an interface to actions not performed by the `Request`.
  776. init(id: UUID = UUID(),
  777. convertible: URLRequestConvertible,
  778. underlyingQueue: DispatchQueue,
  779. serializationQueue: DispatchQueue,
  780. eventMonitor: EventMonitor?,
  781. interceptor: RequestInterceptor?,
  782. delegate: RequestDelegate) {
  783. self.convertible = convertible
  784. super.init(id: id,
  785. underlyingQueue: underlyingQueue,
  786. serializationQueue: serializationQueue,
  787. eventMonitor: eventMonitor,
  788. interceptor: interceptor,
  789. delegate: delegate)
  790. }
  791. override func reset() {
  792. super.reset()
  793. protectedData.directValue = nil
  794. }
  795. /// Called when `Data` is received by this instance.
  796. ///
  797. /// - Note: Also calls `updateDownloadProgress`.
  798. ///
  799. /// - Parameter data: The `Data` received.
  800. func didReceive(data: Data) {
  801. if self.data == nil {
  802. protectedData.directValue = data
  803. } else {
  804. protectedData.append(data)
  805. }
  806. updateDownloadProgress()
  807. }
  808. override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask {
  809. let copiedRequest = request
  810. return session.dataTask(with: copiedRequest)
  811. }
  812. /// Called to updated the `downloadProgress` of the instance.
  813. func updateDownloadProgress() {
  814. let totalBytesReceived = Int64(data?.count ?? 0)
  815. let totalBytesExpected = task?.response?.expectedContentLength ?? NSURLSessionTransferSizeUnknown
  816. downloadProgress.totalUnitCount = totalBytesExpected
  817. downloadProgress.completedUnitCount = totalBytesReceived
  818. downloadProgressHandler?.queue.async { self.downloadProgressHandler?.handler(self.downloadProgress) }
  819. }
  820. /// Validates the request, using the specified closure.
  821. ///
  822. /// - Note: If validation fails, subsequent calls to response handlers will have an associated error.
  823. ///
  824. /// - Parameter validation: `Validation` closure used to validate the response.
  825. ///
  826. /// - Returns: The instance.
  827. @discardableResult
  828. public func validate(_ validation: @escaping Validation) -> Self {
  829. let validator: () -> Void = { [unowned self] in
  830. guard self.error == nil, let response = self.response else { return }
  831. let result = validation(self.request, response, self.data)
  832. if case .failure(let error) = result { self.error = error.asAFError(or: .responseValidationFailed(reason: .customValidationFailed(error: error))) }
  833. self.eventMonitor?.request(self,
  834. didValidateRequest: self.request,
  835. response: response,
  836. data: self.data,
  837. withResult: result)
  838. }
  839. protectedValidators.append(validator)
  840. return self
  841. }
  842. }
  843. // MARK: - DownloadRequest
  844. /// `Request` subclass which downloads `Data` to a file on disk using `URLSessionDownloadTask`.
  845. public class DownloadRequest: Request {
  846. /// A set of options to be executed prior to moving a downloaded file from the temporary `URL` to the destination
  847. /// `URL`.
  848. public struct Options: OptionSet {
  849. /// Specifies that intermediate directories for the destination URL should be created.
  850. public static let createIntermediateDirectories = Options(rawValue: 1 << 0)
  851. /// Specifies that any previous file at the destination `URL` should be removed.
  852. public static let removePreviousFile = Options(rawValue: 1 << 1)
  853. /// Returns the raw bitmask value of the option and satisfies the `RawRepresentable` protocol.
  854. public let rawValue: Int
  855. public init(rawValue: Int) {
  856. self.rawValue = rawValue
  857. }
  858. }
  859. // MARK: Destination
  860. /// A closure executed once a download request has successfully completed in order to determine where to move the
  861. /// temporary file written to during the download process. The closure takes two arguments: the temporary file URL
  862. /// and the URL response, and returns a two arguments: the file URL where the temporary file should be moved and
  863. /// the options defining how the file should be moved.
  864. public typealias Destination = (_ temporaryURL: URL,
  865. _ response: HTTPURLResponse) -> (destinationURL: URL, options: Options)
  866. // MARK: Destination
  867. /// Creates a download file destination closure which uses the default file manager to move the temporary file to a
  868. /// file URL in the first available directory with the specified search path directory and search path domain mask.
  869. ///
  870. /// - Parameters:
  871. /// - directory: The search path directory. `.documentDirectory` by default.
  872. /// - domain: The search path domain mask. `.userDomainMask` by default.
  873. /// - options: `DownloadRequest.Options` used when moving the downloaded file to its destination. None by
  874. /// default.
  875. /// - Returns: The `Destination` closure.
  876. public class func suggestedDownloadDestination(for directory: FileManager.SearchPathDirectory = .documentDirectory,
  877. in domain: FileManager.SearchPathDomainMask = .userDomainMask,
  878. options: Options = []) -> Destination {
  879. return { temporaryURL, response in
  880. let directoryURLs = FileManager.default.urls(for: directory, in: domain)
  881. let url = directoryURLs.first?.appendingPathComponent(response.suggestedFilename!) ?? temporaryURL
  882. return (url, options)
  883. }
  884. }
  885. /// Default `Destination` used by Alamofire to ensure all downloads persist. This `Destination` prepends
  886. /// `Alamofire_` to the automatically generated download name and moves it within the temporary directory. Files
  887. /// with this destination must be additionally moved if they should survive the system reclamation of temporary
  888. /// space.
  889. static let defaultDestination: Destination = { (url, _) in
  890. let filename = "Alamofire_\(url.lastPathComponent)"
  891. let destination = url.deletingLastPathComponent().appendingPathComponent(filename)
  892. return (destination, [])
  893. }
  894. /// Type describing the source used to create the underlying `URLSessionDownloadTask`.
  895. public enum Downloadable {
  896. /// Download should be started from the `URLRequest` produced by the associated `URLRequestConvertible` value.
  897. case request(URLRequestConvertible)
  898. /// Download should be started from the associated resume `Data` value.
  899. case resumeData(Data)
  900. }
  901. // MARK: Mutable State
  902. /// Type containing all mutable state for `DownloadRequest` instances.
  903. private struct DownloadRequestMutableState {
  904. /// Possible resume `Data` produced when cancelling the instance.
  905. var resumeData: Data?
  906. /// `URL` to which `Data` is being downloaded.
  907. var fileURL: URL?
  908. }
  909. /// Protected mutable state specific to `DownloadRequest`.
  910. private let protectedDownloadMutableState: Protector<DownloadRequestMutableState> = Protector(DownloadRequestMutableState())
  911. /// If the download is resumable and eventually cancelled, this value may be used to resume the download using the
  912. /// `download(resumingWith data:)` API.
  913. ///
  914. /// - Note: For more information about `resumeData`, see [Apple's documentation](https://developer.apple.com/documentation/foundation/urlsessiondownloadtask/1411634-cancel).
  915. public var resumeData: Data? { return protectedDownloadMutableState.directValue.resumeData }
  916. /// If the download is successful, the `URL` where the file was downloaded.
  917. public var fileURL: URL? { return protectedDownloadMutableState.directValue.fileURL }
  918. // MARK: Initial State
  919. /// `Downloadable` value used for this instance.
  920. public let downloadable: Downloadable
  921. /// The `Destination` to which the downloaded file is moved.
  922. let destination: Destination
  923. /// Creates a `DownloadRequest` using the provided parameters.
  924. ///
  925. /// - Parameters:
  926. /// - id: `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()` by default.
  927. /// - downloadable: `Downloadable` value used to create `URLSessionDownloadTasks` for the instance.
  928. /// - underlyingQueue: `DispatchQueue` on which all internal `Request` work is performed.
  929. /// - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default targets
  930. /// `underlyingQueue`, but can be passed another queue from a `Session`.
  931. /// - eventMonitor: `EventMonitor` called for event callbacks from internal `Request` actions.
  932. /// - interceptor: `RequestInterceptor` used throughout the request lifecycle.
  933. /// - delegate: `RequestDelegate` that provides an interface to actions not performed by the `Request`
  934. /// - destination: `Destination` closure used to move the downloaded file to its final location.
  935. init(id: UUID = UUID(),
  936. downloadable: Downloadable,
  937. underlyingQueue: DispatchQueue,
  938. serializationQueue: DispatchQueue,
  939. eventMonitor: EventMonitor?,
  940. interceptor: RequestInterceptor?,
  941. delegate: RequestDelegate,
  942. destination: @escaping Destination) {
  943. self.downloadable = downloadable
  944. self.destination = destination
  945. super.init(id: id,
  946. underlyingQueue: underlyingQueue,
  947. serializationQueue: serializationQueue,
  948. eventMonitor: eventMonitor,
  949. interceptor: interceptor,
  950. delegate: delegate)
  951. }
  952. override func reset() {
  953. super.reset()
  954. protectedDownloadMutableState.write {
  955. $0.resumeData = nil
  956. $0.fileURL = nil
  957. }
  958. }
  959. /// Called when a download has finished.
  960. ///
  961. /// - Parameters:
  962. /// - task: `URLSessionTask` that finished the download.
  963. /// - result: `Result` of the automatic move to `destination`.
  964. func didFinishDownloading(using task: URLSessionTask, with result: Result<URL, AFError>) {
  965. eventMonitor?.request(self, didFinishDownloadingUsing: task, with: result)
  966. switch result {
  967. case .success(let url): protectedDownloadMutableState.write { $0.fileURL = url }
  968. case .failure(let error): self.error = error
  969. }
  970. }
  971. /// Updates the `downloadProgress` using the provided values.
  972. ///
  973. /// - Parameters:
  974. /// - bytesWritten: Total bytes written so far.
  975. /// - totalBytesExpectedToWrite: Total bytes expected to write.
  976. func updateDownloadProgress(bytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
  977. downloadProgress.totalUnitCount = totalBytesExpectedToWrite
  978. downloadProgress.completedUnitCount += bytesWritten
  979. downloadProgressHandler?.queue.async { self.downloadProgressHandler?.handler(self.downloadProgress) }
  980. }
  981. override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask {
  982. return session.downloadTask(with: request)
  983. }
  984. /// Creates a `URLSessionTask` from the provided resume data.
  985. ///
  986. /// - Parameters:
  987. /// - data: `Data` used to resume the download.
  988. /// - session: `URLSession` used to create the `URLSessionTask`.
  989. ///
  990. /// - Returns: The `URLSessionTask` created.
  991. public func task(forResumeData data: Data, using session: URLSession) -> URLSessionTask {
  992. return session.downloadTask(withResumeData: data)
  993. }
  994. /// Cancels the instance. Once cancelled, a `DownloadRequest` can no longer be resumed or suspended.
  995. ///
  996. /// - Note: This method will NOT produce resume data. If you wish to cancel and produce resume data, use
  997. /// `cancel(producingResumeData:)` or `cancel(byProducingResumeData:)`.
  998. ///
  999. /// - Returns: The instance.
  1000. @discardableResult
  1001. public override func cancel() -> Self {
  1002. return cancel(producingResumeData: false)
  1003. }
  1004. /// Cancels the instance, optionally producing resume data. Once cancelled, a `DownloadRequest` can no longer be
  1005. /// resumed or suspended.
  1006. ///
  1007. /// - Note: If `producingResumeData` is `true`, the `resumeData` property will be populated with any resume data, if
  1008. /// available.
  1009. ///
  1010. /// - Returns: The instance.
  1011. @discardableResult
  1012. public func cancel(producingResumeData shouldProduceResumeData: Bool) -> Self {
  1013. return cancel(optionallyProducingResumeData: (shouldProduceResumeData) ? { _ in } : nil)
  1014. }
  1015. /// Cancels the instance while producing resume data. Once cancelled, a `DownloadRequest` can no longer be resumed
  1016. /// or suspended.
  1017. ///
  1018. /// - Note: The resume data passed to the completion handler will also be available on the instance's `resumeData`
  1019. /// property.
  1020. ///
  1021. /// - Parameter completionHandler: The completion handler that is called when the download has been successfully
  1022. /// cancelled. It is not guaranteed to be called on a particular queue, so you may
  1023. /// want use an appropriate queue to perform your work.
  1024. ///
  1025. /// - Returns: The instance.
  1026. @discardableResult
  1027. public func cancel(byProducingResumeData completionHandler: @escaping (_ data: Data?) -> Void) -> Self {
  1028. return cancel(optionallyProducingResumeData: completionHandler)
  1029. }
  1030. /// Internal implementation of cancellation that optionally takes a resume data handler. If no handler is passed,
  1031. /// cancellation is performed without producing resume data.
  1032. ///
  1033. /// - Parameter completionHandler: Optional resume data handler.
  1034. ///
  1035. /// - Returns: The instance.
  1036. private func cancel(optionallyProducingResumeData completionHandler: ((_ resumeData: Data?) -> Void)?) -> Self {
  1037. protectedMutableState.write { (mutableState) in
  1038. guard mutableState.state.canTransitionTo(.cancelled) else { return }
  1039. mutableState.state = .cancelled
  1040. underlyingQueue.async { self.didCancel() }
  1041. guard let task = mutableState.tasks.last as? URLSessionDownloadTask, task.state != .completed else {
  1042. underlyingQueue.async { self.finish() }
  1043. return
  1044. }
  1045. if let completionHandler = completionHandler {
  1046. // Resume to ensure metrics are gathered.
  1047. task.resume()
  1048. task.cancel { (resumeData) in
  1049. self.protectedDownloadMutableState.write { $0.resumeData = resumeData }
  1050. self.underlyingQueue.async { self.didCancelTask(task) }
  1051. completionHandler(resumeData)
  1052. }
  1053. } else {
  1054. // Resume to ensure metrics are gathered.
  1055. task.resume()
  1056. task.cancel()
  1057. self.underlyingQueue.async { self.didCancelTask(task) }
  1058. }
  1059. }
  1060. return self
  1061. }
  1062. /// Validates the request, using the specified closure.
  1063. ///
  1064. /// - Note: If validation fails, subsequent calls to response handlers will have an associated error.
  1065. ///
  1066. /// - Parameter validation: `Validation` closure to validate the response.
  1067. ///
  1068. /// - Returns: The instance.
  1069. @discardableResult
  1070. public func validate(_ validation: @escaping Validation) -> Self {
  1071. let validator: () -> Void = { [unowned self] in
  1072. guard self.error == nil, let response = self.response else { return }
  1073. let result = validation(self.request, response, self.fileURL)
  1074. if case .failure(let error) = result { self.error = error.asAFError(or: .responseValidationFailed(reason: .customValidationFailed(error: error))) }
  1075. self.eventMonitor?.request(self,
  1076. didValidateRequest: self.request,
  1077. response: response,
  1078. fileURL: self.fileURL,
  1079. withResult: result)
  1080. }
  1081. protectedValidators.append(validator)
  1082. return self
  1083. }
  1084. }
  1085. // MARK: - UploadRequest
  1086. /// `DataRequest` subclass which handles `Data` upload from memory, file, or stream using `URLSessionUploadTask`.
  1087. public class UploadRequest: DataRequest {
  1088. /// Type describing the origin of the upload, whether `Data`, file, or stream.
  1089. public enum Uploadable {
  1090. /// Upload from the provided `Data` value.
  1091. case data(Data)
  1092. /// Upload from the provided file `URL`, as well as a `Bool` determining whether the source file should be
  1093. /// automatically removed once uploaded.
  1094. case file(URL, shouldRemove: Bool)
  1095. /// Upload from the provided `InputStream`.
  1096. case stream(InputStream)
  1097. }
  1098. // MARK: Initial State
  1099. /// The `UploadableConvertible` value used to produce the `Uploadable` value for this instance.
  1100. public let upload: UploadableConvertible
  1101. /// `FileManager` used to perform cleanup tasks, including the removal of multipart form encoded payloads written
  1102. /// to disk.
  1103. public let fileManager: FileManager
  1104. // MARK: Mutable State
  1105. /// `Uploadable` value used by the instance.
  1106. public var uploadable: Uploadable?
  1107. /// Creates an `UploadRequest` using the provided parameters.
  1108. ///
  1109. /// - Parameters:
  1110. /// - id: `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()` by default.
  1111. /// - convertible: `UploadConvertible` value used to determine the type of upload to be performed.
  1112. /// - underlyingQueue: `DispatchQueue` on which all internal `Request` work is performed.
  1113. /// - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default targets
  1114. /// `underlyingQueue`, but can be passed another queue from a `Session`.
  1115. /// - eventMonitor: `EventMonitor` called for event callbacks from internal `Request` actions.
  1116. /// - interceptor: `RequestInterceptor` used throughout the request lifecycle.
  1117. /// - delegate: `RequestDelegate` that provides an interface to actions not performed by the `Request`.
  1118. init(id: UUID = UUID(),
  1119. convertible: UploadConvertible,
  1120. underlyingQueue: DispatchQueue,
  1121. serializationQueue: DispatchQueue,
  1122. eventMonitor: EventMonitor?,
  1123. interceptor: RequestInterceptor?,
  1124. fileManager: FileManager,
  1125. delegate: RequestDelegate) {
  1126. self.upload = convertible
  1127. self.fileManager = fileManager
  1128. super.init(id: id,
  1129. convertible: convertible,
  1130. underlyingQueue: underlyingQueue,
  1131. serializationQueue: serializationQueue,
  1132. eventMonitor: eventMonitor,
  1133. interceptor: interceptor,
  1134. delegate: delegate)
  1135. }
  1136. /// Called when the `Uploadable` value has been created from the `UploadConvertible`.
  1137. ///
  1138. /// - Parameter uploadable: The `Uploadable` that was created.
  1139. func didCreateUploadable(_ uploadable: Uploadable) {
  1140. self.uploadable = uploadable
  1141. eventMonitor?.request(self, didCreateUploadable: uploadable)
  1142. }
  1143. /// Called when the `Uploadable` value could not be created.
  1144. ///
  1145. /// - Parameter error: `AFError` produced by the failure.
  1146. func didFailToCreateUploadable(with error: AFError) {
  1147. self.error = error
  1148. eventMonitor?.request(self, didFailToCreateUploadableWithError: error)
  1149. retryOrFinish(error: error)
  1150. }
  1151. override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask {
  1152. guard let uploadable = uploadable else {
  1153. fatalError("Attempting to create a URLSessionUploadTask when Uploadable value doesn't exist.")
  1154. }
  1155. switch uploadable {
  1156. case let .data(data): return session.uploadTask(with: request, from: data)
  1157. case let .file(url, _): return session.uploadTask(with: request, fromFile: url)
  1158. case .stream: return session.uploadTask(withStreamedRequest: request)
  1159. }
  1160. }
  1161. /// Produces the `InputStream` from `uploadable`, if it can.
  1162. ///
  1163. /// - Note: Calling this method with a non-`.stream` `Uploadable` is a logic error and will crash.
  1164. ///
  1165. /// - Returns: The `InputStream`.
  1166. func inputStream() -> InputStream {
  1167. guard let uploadable = uploadable else {
  1168. fatalError("Attempting to access the input stream but the uploadable doesn't exist.")
  1169. }
  1170. guard case let .stream(stream) = uploadable else {
  1171. fatalError("Attempted to access the stream of an UploadRequest that wasn't created with one.")
  1172. }
  1173. eventMonitor?.request(self, didProvideInputStream: stream)
  1174. return stream
  1175. }
  1176. public override func cleanup() {
  1177. defer { super.cleanup() }
  1178. guard
  1179. let uploadable = self.uploadable,
  1180. case let .file(url, shouldRemove) = uploadable,
  1181. shouldRemove
  1182. else { return }
  1183. try? fileManager.removeItem(at: url)
  1184. }
  1185. }
  1186. /// A type that can produce an `UploadRequest.Uploadable` value.
  1187. public protocol UploadableConvertible {
  1188. /// Produces an `UploadRequest.Uploadable` value from the instance.
  1189. ///
  1190. /// - Returns: The `UploadRequest.Uploadable`.
  1191. /// - Throws: Any `Error` produced during creation.
  1192. func createUploadable() throws -> UploadRequest.Uploadable
  1193. }
  1194. extension UploadRequest.Uploadable: UploadableConvertible {
  1195. public func createUploadable() throws -> UploadRequest.Uploadable {
  1196. return self
  1197. }
  1198. }
  1199. /// A type that can be converted to an upload, whether from an `UploadRequest.Uploadable` or `URLRequestConvertible`.
  1200. public protocol UploadConvertible: UploadableConvertible & URLRequestConvertible { }