Session.swift 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002
  1. //
  2. // Session.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. /// `Session` creates and manages Alamofire's `Request` types during their lifetimes. It also provides common
  26. /// functionality for all `Request`s, including queuing, interception, trust management, redirect handling, and response
  27. /// cache handling.
  28. open class Session {
  29. /// Shared singleton instance used by all `AF.request` APIs. Cannot be modified.
  30. public static let `default` = Session()
  31. /// Underlying `URLSession` used to create `URLSessionTasks` for this instance, and for which this instance's
  32. /// `delegate` handles `URLSessionDelegate` callbacks.
  33. public let session: URLSession
  34. /// Instance's `SessionDelegate`, which handles the `URLSessionDelegate` methods and `Request` interaction.
  35. public let delegate: SessionDelegate
  36. /// Root `DispatchQueue` for all internal callbacks and state update. **MUST** be a serial queue.
  37. public let rootQueue: DispatchQueue
  38. /// Value determining whether this instance automatically calls `resume()` on all created `Request`s.
  39. public let startRequestsImmediately: Bool
  40. /// `DispatchQueue` on which `URLRequest`s are created asynchronously. By default this queue uses `rootQueue` as its
  41. /// `target`, but a separate queue can be used if request creation is determined to be a bottleneck. Always profile
  42. /// and test before introduing an additional queue.
  43. public let requestQueue: DispatchQueue
  44. /// `DispatchQueue` passed to all `Request`s on which they perform their response serialization. By default this
  45. /// queue uses `rootQueue` as its `target` but a separate queue can be used if response serialization is determined
  46. /// to be a bottleneck. Always profile and test before introducing an additional queue.
  47. public let serializationQueue: DispatchQueue
  48. /// `RequestInterceptor` used for all `Request` created by the instance. `RequestInterceptor`s can also be set on a
  49. /// per-`Request` basis, in which case the `Request`'s interceptor takes precedence over this value.
  50. public let interceptor: RequestInterceptor?
  51. /// `ServerTrustManager` instance used to evaluate all trust challenges and provide certificate and key pinning.
  52. public let serverTrustManager: ServerTrustManager?
  53. /// `RedirectHandler` instance used to provide customization for request redirection.
  54. public let redirectHandler: RedirectHandler?
  55. /// `CachedResponseHandler` instance used to provide customization of cached response handling.
  56. public let cachedResponseHandler: CachedResponseHandler?
  57. /// `CompositeEventMonitor` used to compose Alamofire's `defaultEventMonitors` and any passed `EventMonitor`s.
  58. public let eventMonitor: CompositeEventMonitor
  59. /// `EventMonitor`s included in all instances. `[AlamofireNotifications()]` by default.
  60. public let defaultEventMonitors: [EventMonitor] = [AlamofireNotifications()]
  61. /// Internal map between `Request`s and any `URLSessionTasks` that may be in flight for them.
  62. var requestTaskMap = RequestTaskMap()
  63. /// Set of currently active `Request`s.
  64. var activeRequests: Set<Request> = []
  65. /// Creates a `Session` from a `URLSession` and other parameters.
  66. ///
  67. /// - Note: When passing a `URLSession`, you must create the `URLSession` with a specific `delegateQueue` value and
  68. /// pass the `delegateQueue`'s `underlyingQueue` as the `rootQueue` parameter of this initializer.
  69. ///
  70. /// - Parameters:
  71. /// - session: Underlying `URLSession` for this instance.
  72. /// - delegate: `SessionDelegate` that handles `session`'s delegate callbacks as well as `Request`
  73. /// interaction.
  74. /// - rootQueue: Root `DispatchQueue` for all internal callbacks and state updats. **MUST** be a
  75. /// serial queue.
  76. /// - startRequestsImmediately: Determines whether this instance will automatically start all `Request`s. `true`
  77. /// by default. If set to `false`, all `Request`s created must have `.resume()` called.
  78. /// on them for them to start.
  79. /// - requestQueue: `DispatchQueue` on which to perform `URLRequest` creation. By default this queue
  80. /// will use the `rootQueue` as its `target`. A separate queue can be used if it's
  81. /// determined request creation is a bottleneck, but that should only be done after
  82. /// careful testing and profiling. `nil` by default.
  83. /// - serializationQueue: `DispatchQueue` on which to perform all response serialization. By default this
  84. /// queue will use the `rootQueue` as its `target`. A separate queue can be used if
  85. /// it's determined response serialization is a bottleneck, but that should only be
  86. /// done after careful testing and profiling. `nil` by default.
  87. /// - interceptor: `RequestInterceptor` to be used for all `Request`s created by this instance. `nil`
  88. /// by default.
  89. /// - serverTrustManager: `ServerTrustManager` to be used for all trust evaluations by this instance. `nil`
  90. /// by default.
  91. /// - redirectHandler: `RedirectHandler` to be used by all `Request`s created by this instance. `nil` by
  92. /// default.
  93. /// - cachedResponseHandler: `CachedResponseHandler` to be used by all `Request`s created by this instance.
  94. /// `nil` by default.
  95. /// - eventMonitors: Additional `EventMonitor`s used by the instance. Alamofire always adds a
  96. /// `AlamofireNotifications` `EventMonitor` to the array passed here. `[]` by default.
  97. public init(session: URLSession,
  98. delegate: SessionDelegate,
  99. rootQueue: DispatchQueue,
  100. startRequestsImmediately: Bool = true,
  101. requestQueue: DispatchQueue? = nil,
  102. serializationQueue: DispatchQueue? = nil,
  103. interceptor: RequestInterceptor? = nil,
  104. serverTrustManager: ServerTrustManager? = nil,
  105. redirectHandler: RedirectHandler? = nil,
  106. cachedResponseHandler: CachedResponseHandler? = nil,
  107. eventMonitors: [EventMonitor] = []) {
  108. precondition(session.delegateQueue.underlyingQueue === rootQueue,
  109. "Session(session:) intializer must be passed the DispatchQueue used as the delegateQueue's underlyingQueue as rootQueue.")
  110. self.session = session
  111. self.delegate = delegate
  112. self.rootQueue = rootQueue
  113. self.startRequestsImmediately = startRequestsImmediately
  114. self.requestQueue = requestQueue ?? DispatchQueue(label: "\(rootQueue.label).requestQueue", target: rootQueue)
  115. self.serializationQueue = serializationQueue ?? DispatchQueue(label: "\(rootQueue.label).serializationQueue", target: rootQueue)
  116. self.interceptor = interceptor
  117. self.serverTrustManager = serverTrustManager
  118. self.redirectHandler = redirectHandler
  119. self.cachedResponseHandler = cachedResponseHandler
  120. eventMonitor = CompositeEventMonitor(monitors: defaultEventMonitors + eventMonitors)
  121. delegate.eventMonitor = eventMonitor
  122. delegate.stateProvider = self
  123. }
  124. /// Creates a `Session` from a `URLSessionConfiguration`.
  125. ///
  126. /// - Note: This intializer lets Alamofire handle the creation of the underlying `URLSession` and its
  127. /// `delegateQueue`, and is the recommended intiailizer for most uses.
  128. ///
  129. /// - Parameters:
  130. /// - configuration: `URLSessionConfiguration` to be used to create the underlying `URLSession`. Changes
  131. /// to this value after being passed to this initializer will have no effect.
  132. /// `URLSessionConfiguration.af.default` by default.
  133. /// - delegate: `SessionDelegate` that handles `session`'s delegate callbacks as well as `Request`
  134. /// interaction. `SessionDelegate()` by default.
  135. /// - rootQueue: Root `DispatchQueue` for all internal callbacks and state updats. **MUST** be a
  136. /// serial queue. `DispatchQueue(label: "org.alamofire.session.rootQueue")` by default.
  137. /// - startRequestsImmediately: Determines whether this instance will automatically start all `Request`s. `true`
  138. /// by default. If set to `false`, all `Request`s created must have `.resume()` called.
  139. /// on them for them to start.
  140. /// - requestQueue: `DispatchQueue` on which to perform `URLRequest` creation. By default this queue
  141. /// will use the `rootQueue` as its `target`. A separate queue can be used if it's
  142. /// determined request creation is a bottleneck, but that should only be done after
  143. /// careful testing and profiling. `nil` by default.
  144. /// - serializationQueue: `DispatchQueue` on which to perform all response serialization. By default this
  145. /// queue will use the `rootQueue` as its `target`. A separate queue can be used if
  146. /// it's determined response serialization is a bottleneck, but that should only be
  147. /// done after careful testing and profiling. `nil` by default.
  148. /// - interceptor: `RequestInterceptor` to be used for all `Request`s created by this instance. `nil`
  149. /// by default.
  150. /// - serverTrustManager: `ServerTrustManager` to be used for all trust evaluations by this instance. `nil`
  151. /// by default.
  152. /// - redirectHandler: `RedirectHandler` to be used by all `Request`s created by this instance. `nil` by
  153. /// default.
  154. /// - cachedResponseHandler: `CachedResponseHandler` to be used by all `Request`s created by this instance.
  155. /// `nil` by default.
  156. /// - eventMonitors: Additional `EventMonitor`s used by the instance. Alamofire always adds a
  157. /// `AlamofireNotifications` `EventMonitor` to the array passed here. `[]` by default.
  158. public convenience init(configuration: URLSessionConfiguration = URLSessionConfiguration.af.default,
  159. delegate: SessionDelegate = SessionDelegate(),
  160. rootQueue: DispatchQueue = DispatchQueue(label: "org.alamofire.session.rootQueue"),
  161. startRequestsImmediately: Bool = true,
  162. requestQueue: DispatchQueue? = nil,
  163. serializationQueue: DispatchQueue? = nil,
  164. interceptor: RequestInterceptor? = nil,
  165. serverTrustManager: ServerTrustManager? = nil,
  166. redirectHandler: RedirectHandler? = nil,
  167. cachedResponseHandler: CachedResponseHandler? = nil,
  168. eventMonitors: [EventMonitor] = []) {
  169. let delegateQueue = OperationQueue(maxConcurrentOperationCount: 1, underlyingQueue: rootQueue, name: "org.alamofire.session.sessionDelegateQueue")
  170. let session = URLSession(configuration: configuration, delegate: delegate, delegateQueue: delegateQueue)
  171. self.init(session: session,
  172. delegate: delegate,
  173. rootQueue: rootQueue,
  174. startRequestsImmediately: startRequestsImmediately,
  175. requestQueue: requestQueue,
  176. serializationQueue: serializationQueue,
  177. interceptor: interceptor,
  178. serverTrustManager: serverTrustManager,
  179. redirectHandler: redirectHandler,
  180. cachedResponseHandler: cachedResponseHandler,
  181. eventMonitors: eventMonitors)
  182. }
  183. deinit {
  184. finishRequestsForDeinit()
  185. session.invalidateAndCancel()
  186. }
  187. // MARK: - Cancellation
  188. /// Cancel all active `Request`s, optionally calling a completion handler when complete.
  189. ///
  190. /// - Note: This is an asynchronous operation and does not block the creation of future `Request`s. Cancelled
  191. /// `Request`s may not cancel immediately due internal work, and may not cancel at all if they are close to
  192. /// completion when cancelled.
  193. ///
  194. /// - Parameters:
  195. /// - queue: `DispatchQueue` on which the completion handler is run. `.main` by default.
  196. /// - completion: Closure to be called when all `Request`s have been cancelled.
  197. public func cancelAllRequests(completingOnQueue queue: DispatchQueue = .main, completion: (() -> Void)? = nil) {
  198. rootQueue.async {
  199. self.activeRequests.forEach { $0.cancel() }
  200. queue.async { completion?() }
  201. }
  202. }
  203. // MARK: - DataRequest
  204. struct RequestConvertible: URLRequestConvertible {
  205. let url: URLConvertible
  206. let method: HTTPMethod
  207. let parameters: Parameters?
  208. let encoding: ParameterEncoding
  209. let headers: HTTPHeaders?
  210. func asURLRequest() throws -> URLRequest {
  211. let request = try URLRequest(url: url, method: method, headers: headers)
  212. return try encoding.encode(request, with: parameters)
  213. }
  214. }
  215. /// Creates a `DataRequest` from a `URLRequest` created using the passeed components and a `RequestInterceptor`.
  216. ///
  217. /// - Parameters:
  218. /// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`.
  219. /// - method: `HTTPMethod` for the `URLRequest`. `.get` by default.
  220. /// - parameters: `Parameters` (a.k.a. `[String: Any]`) value to be encoded into the `URLRequest`. `nil` by default.
  221. /// - encoding: `ParameterEncoding` to be used to encode the `parameters` value into the `URLRequest`.
  222. /// `URLEncoding.default` by default.
  223. /// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default.
  224. /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
  225. ///
  226. /// - Returns: The created `DataRequest`.
  227. open func request(_ convertible: URLConvertible,
  228. method: HTTPMethod = .get,
  229. parameters: Parameters? = nil,
  230. encoding: ParameterEncoding = URLEncoding.default,
  231. headers: HTTPHeaders? = nil,
  232. interceptor: RequestInterceptor? = nil) -> DataRequest {
  233. let convertible = RequestConvertible(url: convertible,
  234. method: method,
  235. parameters: parameters,
  236. encoding: encoding,
  237. headers: headers)
  238. return request(convertible, interceptor: interceptor)
  239. }
  240. struct RequestEncodableConvertible<Parameters: Encodable>: URLRequestConvertible {
  241. let url: URLConvertible
  242. let method: HTTPMethod
  243. let parameters: Parameters?
  244. let encoder: ParameterEncoder
  245. let headers: HTTPHeaders?
  246. func asURLRequest() throws -> URLRequest {
  247. let request = try URLRequest(url: url, method: method, headers: headers)
  248. return try parameters.map { try encoder.encode($0, into: request) } ?? request
  249. }
  250. }
  251. /// Creates a `DataRequest` from a `URLRequest` created using the passed components, `Encodable` parameters, and a
  252. /// `RequestInterceptor`.
  253. ///
  254. /// - Parameters:
  255. /// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`.
  256. /// - method: `HTTPMethod` for the `URLRequest`. `.get` by default.
  257. /// - parameters: Value conforming to `Encodable` to be encoded into the `URLRequest`. `nil` by default.
  258. /// - encoder: `ParameterEncoder` to be used to encode the `parameters` value into the `URLRequest`.
  259. /// `URLEncodedFormParameterEncoder.default` by default.
  260. /// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default.
  261. /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
  262. ///
  263. /// - Returns: The created `DataRequest`.
  264. open func request<Parameters: Encodable>(_ convertible: URLConvertible,
  265. method: HTTPMethod = .get,
  266. parameters: Parameters? = nil,
  267. encoder: ParameterEncoder = URLEncodedFormParameterEncoder.default,
  268. headers: HTTPHeaders? = nil,
  269. interceptor: RequestInterceptor? = nil) -> DataRequest {
  270. let convertible = RequestEncodableConvertible(url: convertible,
  271. method: method,
  272. parameters: parameters,
  273. encoder: encoder,
  274. headers: headers)
  275. return request(convertible, interceptor: interceptor)
  276. }
  277. /// Creates a `DataRequest` from a `URLRequestConvertible` value and a `RequestInterceptor`.
  278. ///
  279. /// - Parameters:
  280. /// - convertible: `URLRequestConvertible` value to be used to create the `URLRequest`.
  281. /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
  282. ///
  283. /// - Returns: The created `DataRequest`.
  284. open func request(_ convertible: URLRequestConvertible, interceptor: RequestInterceptor? = nil) -> DataRequest {
  285. let request = DataRequest(convertible: convertible,
  286. underlyingQueue: rootQueue,
  287. serializationQueue: serializationQueue,
  288. eventMonitor: eventMonitor,
  289. interceptor: interceptor,
  290. delegate: self)
  291. perform(request)
  292. return request
  293. }
  294. // MARK: - DownloadRequest
  295. /// Creates a `DownloadRequest` using a `URLRequest` created using the passed components, `RequestInterceptor`, and
  296. /// `Destination`.
  297. ///
  298. /// - Parameters:
  299. /// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`.
  300. /// - method: `HTTPMethod` for the `URLRequest`. `.get` by default.
  301. /// - parameters: `Parameters` (a.k.a. `[String: Any]`) value to be encoded into the `URLRequest`. `nil` by default.
  302. /// - encoding: `ParameterEncoding` to be used to encode the `parameters` value into the `URLRequest`. Defaults
  303. /// to `URLEncoding.default`.
  304. /// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default.
  305. /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
  306. /// - destination: `DownloadRequest.Destination` closure used to determine how and where the downloaded file
  307. /// should be moved. `nil` by default.
  308. ///
  309. /// - Returns: The created `DownloadRequest`.
  310. open func download(_ convertible: URLConvertible,
  311. method: HTTPMethod = .get,
  312. parameters: Parameters? = nil,
  313. encoding: ParameterEncoding = URLEncoding.default,
  314. headers: HTTPHeaders? = nil,
  315. interceptor: RequestInterceptor? = nil,
  316. to destination: DownloadRequest.Destination? = nil) -> DownloadRequest {
  317. let convertible = RequestConvertible(url: convertible,
  318. method: method,
  319. parameters: parameters,
  320. encoding: encoding,
  321. headers: headers)
  322. return download(convertible, interceptor: interceptor, to: destination)
  323. }
  324. /// Creates a `DownloadRequest` from a `URLRequest` created using the passed components, `Encodable` parameters, and
  325. /// a `RequestInterceptor`.
  326. ///
  327. /// - Parameters:
  328. /// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`.
  329. /// - method: `HTTPMethod` for the `URLRequest`. `.get` by default.
  330. /// - parameters: Value conforming to `Encodable` to be encoded into the `URLRequest`. `nil` by default.
  331. /// - encoder: `ParameterEncoder` to be used to encode the `parameters` value into the `URLRequest`. Defaults
  332. /// to `URLEncodedFormParameterEncoder.default`.
  333. /// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default.
  334. /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
  335. /// - destination: `DownloadRequest.Destination` closure used to determine how and where the downloaded file
  336. /// should be moved. `nil` by default.
  337. ///
  338. /// - Returns: The created `DownloadRequest`.
  339. open func download<Parameters: Encodable>(_ convertible: URLConvertible,
  340. method: HTTPMethod = .get,
  341. parameters: Parameters? = nil,
  342. encoder: ParameterEncoder = URLEncodedFormParameterEncoder.default,
  343. headers: HTTPHeaders? = nil,
  344. interceptor: RequestInterceptor? = nil,
  345. to destination: DownloadRequest.Destination? = nil) -> DownloadRequest {
  346. let convertible = RequestEncodableConvertible(url: convertible,
  347. method: method,
  348. parameters: parameters,
  349. encoder: encoder,
  350. headers: headers)
  351. return download(convertible, interceptor: interceptor, to: destination)
  352. }
  353. /// Creates a `DownloadRequest` from a `URLRequestConvertible` value, a `RequestInterceptor`, and a `Destination`.
  354. ///
  355. /// - Parameters:
  356. /// - convertible: `URLRequestConvertible` value to be used to create the `URLRequest`.
  357. /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
  358. /// - destination: `DownloadRequest.Destination` closure used to determine how and where the downloaded file
  359. /// should be moved. `nil` by default.
  360. ///
  361. /// - Returns: The created `DownloadRequest`.
  362. open func download(_ convertible: URLRequestConvertible,
  363. interceptor: RequestInterceptor? = nil,
  364. to destination: DownloadRequest.Destination? = nil) -> DownloadRequest {
  365. let request = DownloadRequest(downloadable: .request(convertible),
  366. underlyingQueue: rootQueue,
  367. serializationQueue: serializationQueue,
  368. eventMonitor: eventMonitor,
  369. interceptor: interceptor,
  370. delegate: self,
  371. destination: destination ?? DownloadRequest.defaultDestination)
  372. perform(request)
  373. return request
  374. }
  375. /// Creates a `DownloadRequest` from the `resumeData` produced from a previously cancelled `DownloadRequest`, as
  376. /// well as a `RequestInterceptor`, and a `Destination`.
  377. ///
  378. /// - Note: If `destination` is not specified, the download will be moved to a temporary location determined by
  379. /// Alamofire. The file will not be deleted until the system purges the temporary files.
  380. ///
  381. /// - Note: On some versions of all Apple platforms (iOS 10 - 10.2, macOS 10.12 - 10.12.2, tvOS 10 - 10.1, watchOS 3 - 3.1.1),
  382. /// `resumeData` is broken on background URL session configurations. There's an underlying bug in the `resumeData`
  383. /// generation logic where the data is written incorrectly and will always fail to resume the download. For more
  384. /// information about the bug and possible workarounds, please refer to the [this Stack Overflow post](http://stackoverflow.com/a/39347461/1342462).
  385. ///
  386. /// - Parameters:
  387. /// - data: The resume data from a previously cancelled `DownloadRequest` or `URLSessionDownloadTask`.
  388. /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
  389. /// - destination: `DownloadRequest.Destination` closure used to determine how and where the downloaded file
  390. /// should be moved. `nil` by default.
  391. ///
  392. /// - Returns: The created `DownloadRequest`.
  393. open func download(resumingWith data: Data,
  394. interceptor: RequestInterceptor? = nil,
  395. to destination: DownloadRequest.Destination? = nil) -> DownloadRequest {
  396. let request = DownloadRequest(downloadable: .resumeData(data),
  397. underlyingQueue: rootQueue,
  398. serializationQueue: serializationQueue,
  399. eventMonitor: eventMonitor,
  400. interceptor: interceptor,
  401. delegate: self,
  402. destination: destination ?? DownloadRequest.defaultDestination)
  403. perform(request)
  404. return request
  405. }
  406. // MARK: - UploadRequest
  407. struct ParameterlessRequestConvertible: URLRequestConvertible {
  408. let url: URLConvertible
  409. let method: HTTPMethod
  410. let headers: HTTPHeaders?
  411. func asURLRequest() throws -> URLRequest {
  412. return try URLRequest(url: url, method: method, headers: headers)
  413. }
  414. }
  415. struct Upload: UploadConvertible {
  416. let request: URLRequestConvertible
  417. let uploadable: UploadableConvertible
  418. func createUploadable() throws -> UploadRequest.Uploadable {
  419. return try uploadable.createUploadable()
  420. }
  421. func asURLRequest() throws -> URLRequest {
  422. return try request.asURLRequest()
  423. }
  424. }
  425. // MARK: Data
  426. /// Creates an `UploadRequest` for the given `Data`, `URLRequest` components, and `RequestInterceptor`.
  427. ///
  428. /// - Parameters:
  429. /// - data: The `Data` to upload.
  430. /// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`.
  431. /// - method: `HTTPMethod` for the `URLRequest`. `.post` by default.
  432. /// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default.
  433. /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
  434. ///
  435. /// - Returns: The created `UploadRequest`.
  436. open func upload(_ data: Data,
  437. to convertible: URLConvertible,
  438. method: HTTPMethod = .post,
  439. headers: HTTPHeaders? = nil,
  440. interceptor: RequestInterceptor? = nil) -> UploadRequest {
  441. let convertible = ParameterlessRequestConvertible(url: convertible, method: method, headers: headers)
  442. return upload(data, with: convertible, interceptor: interceptor)
  443. }
  444. /// Creates an `UploadRequest` for the given `Data` using the `URLRequestConvertible` value and `RequestInterceptor`.
  445. ///
  446. /// - Parameters:
  447. /// - data: The `Data` to upload.
  448. /// - convertible: `URLRequestConvertible` value to be used to create the `URLRequest`.
  449. /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
  450. ///
  451. /// - Returns: The created `UploadRequest`.
  452. open func upload(_ data: Data,
  453. with convertible: URLRequestConvertible,
  454. interceptor: RequestInterceptor? = nil) -> UploadRequest {
  455. return upload(.data(data), with: convertible, interceptor: interceptor)
  456. }
  457. // MARK: File
  458. /// Creates an `UploadRequest` for the file at the given file `URL`, using a `URLRequest` from the provided
  459. /// components and `RequestInterceptor`.
  460. ///
  461. /// - Parameters:
  462. /// - fileURL: The `URL` of the file to upload.
  463. /// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`.
  464. /// - method: `HTTPMethod` for the `URLRequest`. `.post` by default.
  465. /// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default.
  466. /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
  467. ///
  468. /// - Returns: The created `UploadRequest`.
  469. open func upload(_ fileURL: URL,
  470. to convertible: URLConvertible,
  471. method: HTTPMethod = .post,
  472. headers: HTTPHeaders? = nil,
  473. interceptor: RequestInterceptor? = nil) -> UploadRequest {
  474. let convertible = ParameterlessRequestConvertible(url: convertible, method: method, headers: headers)
  475. return upload(fileURL, with: convertible, interceptor: interceptor)
  476. }
  477. /// Creates an `UploadRequest` for the file at the given file `URL` using the `URLRequestConvertible` value and
  478. /// `RequestInterceptor`.
  479. ///
  480. /// - Parameters:
  481. /// - fileURL: The `URL` of the file to upload.
  482. /// - convertible: `URLRequestConvertible` value to be used to create the `URLRequest`.
  483. /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
  484. ///
  485. /// - Returns: The created `UploadRequest`.
  486. open func upload(_ fileURL: URL,
  487. with convertible: URLRequestConvertible,
  488. interceptor: RequestInterceptor? = nil) -> UploadRequest {
  489. return upload(.file(fileURL, shouldRemove: false), with: convertible, interceptor: interceptor)
  490. }
  491. // MARK: InputStream
  492. /// Creates an `UploadRequest` from the `InputStream` provided using a `URLRequest` from the provided components and
  493. /// `RequestInterceptor`.
  494. ///
  495. /// - Parameters:
  496. /// - stream: The `InputStream` that provides the data to upload.
  497. /// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`.
  498. /// - method: `HTTPMethod` for the `URLRequest`. `.post` by default.
  499. /// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default.
  500. /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
  501. ///
  502. /// - Returns: The created `UploadRequest`.
  503. open func upload(_ stream: InputStream,
  504. to convertible: URLConvertible,
  505. method: HTTPMethod = .post,
  506. headers: HTTPHeaders? = nil,
  507. interceptor: RequestInterceptor? = nil) -> UploadRequest {
  508. let convertible = ParameterlessRequestConvertible(url: convertible, method: method, headers: headers)
  509. return upload(stream, with: convertible, interceptor: interceptor)
  510. }
  511. /// Creates an `UploadRequest` from the provided `InputStream` using the `URLRequestConvertible` value and
  512. /// `RequestInterceptor`.
  513. ///
  514. /// - Parameters:
  515. /// - stream: The `InputStream` that provides the data to upload.
  516. /// - convertible: `URLRequestConvertible` value to be used to create the `URLRequest`.
  517. /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
  518. ///
  519. /// - Returns: The created `UploadRequest`.
  520. open func upload(_ stream: InputStream,
  521. with convertible: URLRequestConvertible,
  522. interceptor: RequestInterceptor? = nil) -> UploadRequest {
  523. return upload(.stream(stream), with: convertible, interceptor: interceptor)
  524. }
  525. // MARK: MultipartFormData
  526. /// Creates an `UploadRequest` for the multipart form data built using a closure and sent using the provided
  527. /// `URLRequest` components and `RequestInterceptor`.
  528. ///
  529. /// It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative
  530. /// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most
  531. /// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to
  532. /// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory
  533. /// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be
  534. /// used for larger payloads such as video content.
  535. ///
  536. /// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory
  537. /// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`,
  538. /// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk
  539. /// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding
  540. /// technique was used.
  541. ///
  542. /// - Parameters:
  543. /// - multipartFormData: `MultipartFormData` building closure.
  544. /// - encodingMemoryThreshold: Byte threshold used to determine whether the form data is encoded into memory or
  545. /// onto disk before being uploaded. `MultipartFormData.encodingMemoryThreshold` by default.
  546. /// - fileManager: `FileManager` to be used if the form data exceeds the memory threshold and is
  547. /// written to disk before being uploaded.
  548. /// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`.
  549. /// - method: `HTTPMethod` for the `URLRequest`. `.post` by default.
  550. /// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default.
  551. /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
  552. ///
  553. /// - Returns: The created `UploadRequest`.
  554. open func upload(multipartFormData: @escaping (MultipartFormData) -> Void,
  555. usingThreshold encodingMemoryThreshold: UInt64 = MultipartFormData.encodingMemoryThreshold,
  556. fileManager: FileManager = .default,
  557. to url: URLConvertible,
  558. method: HTTPMethod = .post,
  559. headers: HTTPHeaders? = nil,
  560. interceptor: RequestInterceptor? = nil) -> UploadRequest {
  561. let convertible = ParameterlessRequestConvertible(url: url, method: method, headers: headers)
  562. let formData = MultipartFormData(fileManager: fileManager)
  563. multipartFormData(formData)
  564. return upload(multipartFormData: formData,
  565. usingThreshold: encodingMemoryThreshold,
  566. with: convertible,
  567. interceptor: interceptor)
  568. }
  569. /// Creates an `UploadRequest` using a `MultipartFormData` building closure, the provided `URLRequestConvertible`
  570. /// value, and a `RequestInterceptor`.
  571. ///
  572. /// It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative
  573. /// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most
  574. /// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to
  575. /// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory
  576. /// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be
  577. /// used for larger payloads such as video content.
  578. ///
  579. /// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory
  580. /// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`,
  581. /// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk
  582. /// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding
  583. /// technique was used.
  584. ///
  585. /// - Parameters:
  586. /// - multipartFormData: `MultipartFormData` building closure.
  587. /// - encodingMemoryThreshold: Byte threshold used to determine whether the form data is encoded into memory or
  588. /// onto disk before being uploaded. `MultipartFormData.encodingMemoryThreshold` by default.
  589. /// - fileManager: `FileManager` to be used if the form data exceeds the memory threshold and is
  590. /// written to disk before being uploaded.
  591. /// - request: `URLRequestConvertible` value to be used to create the `URLRequest`.
  592. /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
  593. ///
  594. /// - Returns: The created `UploadRequest`.
  595. open func upload(multipartFormData: @escaping (MultipartFormData) -> Void,
  596. usingThreshold encodingMemoryThreshold: UInt64 = MultipartFormData.encodingMemoryThreshold,
  597. fileManager: FileManager = .default,
  598. with request: URLRequestConvertible,
  599. interceptor: RequestInterceptor? = nil) -> UploadRequest {
  600. let formData = MultipartFormData(fileManager: fileManager)
  601. multipartFormData(formData)
  602. return upload(multipartFormData: formData,
  603. usingThreshold: encodingMemoryThreshold,
  604. with: request,
  605. interceptor: interceptor)
  606. }
  607. /// Creates an `UploadRequest` for the prebuilt `MultipartFormData` value using the provided `URLRequest` components
  608. /// and `RequestInterceptor`.
  609. ///
  610. /// It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative
  611. /// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most
  612. /// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to
  613. /// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory
  614. /// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be
  615. /// used for larger payloads such as video content.
  616. ///
  617. /// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory
  618. /// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`,
  619. /// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk
  620. /// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding
  621. /// technique was used.
  622. ///
  623. /// - Parameters:
  624. /// - multipartFormData: `MultipartFormData` instance to upload.
  625. /// - encodingMemoryThreshold: Byte threshold used to determine whether the form data is encoded into memory or
  626. /// onto disk before being uploaded. `MultipartFormData.encodingMemoryThreshold` by default.
  627. /// - url: `URLConvertible` value to be used as the `URLRequest`'s `URL`.
  628. /// - method: `HTTPMethod` for the `URLRequest`. `.post` by default.
  629. /// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default.
  630. /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
  631. ///
  632. /// - Returns: The created `UploadRequest`.
  633. open func upload(multipartFormData: MultipartFormData,
  634. usingThreshold encodingMemoryThreshold: UInt64 = MultipartFormData.encodingMemoryThreshold,
  635. to url: URLConvertible,
  636. method: HTTPMethod = .post,
  637. headers: HTTPHeaders? = nil,
  638. interceptor: RequestInterceptor? = nil) -> UploadRequest {
  639. let convertible = ParameterlessRequestConvertible(url: url, method: method, headers: headers)
  640. let multipartUpload = MultipartUpload(isInBackgroundSession: (session.configuration.identifier != nil),
  641. encodingMemoryThreshold: encodingMemoryThreshold,
  642. request: convertible,
  643. multipartFormData: multipartFormData)
  644. return upload(multipartUpload, interceptor: interceptor)
  645. }
  646. /// Creates an `UploadRequest` for the prebuilt `MultipartFormData` value using the providing `URLRequestConvertible`
  647. /// value and `RequestInterceptor`.
  648. ///
  649. /// It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative
  650. /// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most
  651. /// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to
  652. /// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory
  653. /// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be
  654. /// used for larger payloads such as video content.
  655. ///
  656. /// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory
  657. /// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`,
  658. /// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk
  659. /// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding
  660. /// technique was used.
  661. ///
  662. /// - Parameters:
  663. /// - multipartFormData: `MultipartFormData` instance to upload.
  664. /// - encodingMemoryThreshold: Byte threshold used to determine whether the form data is encoded into memory or
  665. /// onto disk before being uploaded. `MultipartFormData.encodingMemoryThreshold` by
  666. /// default.
  667. /// - request: `URLRequestConvertible` value to be used to create the `URLRequest`.
  668. /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
  669. ///
  670. /// - Returns: The created `UploadRequest`.
  671. open func upload(multipartFormData: MultipartFormData,
  672. usingThreshold encodingMemoryThreshold: UInt64 = MultipartFormData.encodingMemoryThreshold,
  673. with request: URLRequestConvertible,
  674. interceptor: RequestInterceptor? = nil) -> UploadRequest {
  675. let multipartUpload = MultipartUpload(isInBackgroundSession: (session.configuration.identifier != nil),
  676. encodingMemoryThreshold: encodingMemoryThreshold,
  677. request: request,
  678. multipartFormData: multipartFormData)
  679. return upload(multipartUpload, interceptor: interceptor)
  680. }
  681. // MARK: - Internal API
  682. // MARK: Uploadable
  683. func upload(_ uploadable: UploadRequest.Uploadable,
  684. with convertible: URLRequestConvertible,
  685. interceptor: RequestInterceptor?) -> UploadRequest {
  686. let uploadable = Upload(request: convertible, uploadable: uploadable)
  687. return upload(uploadable, interceptor: interceptor)
  688. }
  689. func upload(_ upload: UploadConvertible, interceptor: RequestInterceptor?) -> UploadRequest {
  690. let request = UploadRequest(convertible: upload,
  691. underlyingQueue: rootQueue,
  692. serializationQueue: serializationQueue,
  693. eventMonitor: eventMonitor,
  694. interceptor: interceptor,
  695. delegate: self)
  696. perform(request)
  697. return request
  698. }
  699. // MARK: Perform
  700. /// Perform `Request`.
  701. ///
  702. /// - Note: Called during retry.
  703. ///
  704. /// - Parameter request: The `Request` to perform.
  705. func perform(_ request: Request) {
  706. switch request {
  707. case let r as DataRequest: perform(r)
  708. case let r as UploadRequest: perform(r)
  709. case let r as DownloadRequest: perform(r)
  710. default: fatalError("Attempted to perform unsupported Request subclass: \(type(of: request))")
  711. }
  712. }
  713. func perform(_ request: DataRequest) {
  714. requestQueue.async {
  715. guard !request.isCancelled else { return }
  716. self.activeRequests.insert(request)
  717. self.performSetupOperations(for: request, convertible: request.convertible)
  718. }
  719. }
  720. func perform(_ request: UploadRequest) {
  721. requestQueue.async {
  722. guard !request.isCancelled else { return }
  723. self.activeRequests.insert(request)
  724. do {
  725. let uploadable = try request.upload.createUploadable()
  726. self.rootQueue.async { request.didCreateUploadable(uploadable) }
  727. self.performSetupOperations(for: request, convertible: request.convertible)
  728. } catch {
  729. self.rootQueue.async { request.didFailToCreateUploadable(with: error) }
  730. }
  731. }
  732. }
  733. func perform(_ request: DownloadRequest) {
  734. requestQueue.async {
  735. guard !request.isCancelled else { return }
  736. self.activeRequests.insert(request)
  737. switch request.downloadable {
  738. case let .request(convertible):
  739. self.performSetupOperations(for: request, convertible: convertible)
  740. case let .resumeData(resumeData):
  741. self.rootQueue.async { self.didReceiveResumeData(resumeData, for: request) }
  742. }
  743. }
  744. }
  745. func performSetupOperations(for request: Request, convertible: URLRequestConvertible) {
  746. do {
  747. let initialRequest = try convertible.asURLRequest()
  748. rootQueue.async { request.didCreateInitialURLRequest(initialRequest) }
  749. guard !request.isCancelled else { return }
  750. if let adapter = adapter(for: request) {
  751. adapter.adapt(initialRequest, for: self) { result in
  752. do {
  753. let adaptedRequest = try result.get()
  754. self.rootQueue.async {
  755. request.didAdaptInitialRequest(initialRequest, to: adaptedRequest)
  756. self.didCreateURLRequest(adaptedRequest, for: request)
  757. }
  758. } catch {
  759. let adaptError = AFError.requestAdaptationFailed(error: error)
  760. self.rootQueue.async { request.didFailToAdaptURLRequest(initialRequest, withError: adaptError) }
  761. }
  762. }
  763. } else {
  764. rootQueue.async { self.didCreateURLRequest(initialRequest, for: request) }
  765. }
  766. } catch {
  767. rootQueue.async { request.didFailToCreateURLRequest(with: error) }
  768. }
  769. }
  770. // MARK: - Task Handling
  771. func didCreateURLRequest(_ urlRequest: URLRequest, for request: Request) {
  772. request.didCreateURLRequest(urlRequest)
  773. guard !request.isCancelled else { return }
  774. let task = request.task(for: urlRequest, using: session)
  775. requestTaskMap[request] = task
  776. request.didCreateTask(task)
  777. updateStatesForTask(task, request: request)
  778. }
  779. func didReceiveResumeData(_ data: Data, for request: DownloadRequest) {
  780. guard !request.isCancelled else { return }
  781. let task = request.task(forResumeData: data, using: session)
  782. requestTaskMap[request] = task
  783. request.didCreateTask(task)
  784. updateStatesForTask(task, request: request)
  785. }
  786. func updateStatesForTask(_ task: URLSessionTask, request: Request) {
  787. request.withState { (state) in
  788. switch (startRequestsImmediately, state) {
  789. case (true, .initialized):
  790. rootQueue.async { request.resume() }
  791. case (false, .initialized):
  792. // Do nothing.
  793. break
  794. case (_, .resumed):
  795. task.resume()
  796. rootQueue.async { request.didResumeTask(task) }
  797. case (_, .suspended):
  798. task.suspend()
  799. rootQueue.async { request.didSuspendTask(task) }
  800. case (_, .cancelled):
  801. // Resume to ensure metrics are gathered.
  802. task.resume()
  803. task.cancel()
  804. rootQueue.async { request.didCancelTask(task) }
  805. case (_, .finished):
  806. // Do nothing
  807. break
  808. }
  809. }
  810. }
  811. // MARK: - Adapters and Retriers
  812. func adapter(for request: Request) -> RequestAdapter? {
  813. if let requestInterceptor = request.interceptor, let sessionInterceptor = interceptor {
  814. return Interceptor(adapters: [requestInterceptor, sessionInterceptor])
  815. } else {
  816. return request.interceptor ?? interceptor
  817. }
  818. }
  819. func retrier(for request: Request) -> RequestRetrier? {
  820. if let requestInterceptor = request.interceptor, let sessionInterceptor = interceptor {
  821. return Interceptor(retriers: [requestInterceptor, sessionInterceptor])
  822. } else {
  823. return request.interceptor ?? interceptor
  824. }
  825. }
  826. // MARK: - Invalidation
  827. func finishRequestsForDeinit() {
  828. requestTaskMap.requests.forEach { $0.finish(error: AFError.sessionDeinitialized) }
  829. }
  830. }
  831. // MARK: - RequestDelegate
  832. extension Session: RequestDelegate {
  833. public var sessionConfiguration: URLSessionConfiguration {
  834. return session.configuration
  835. }
  836. public func cleanup(after request: Request) {
  837. activeRequests.remove(request)
  838. }
  839. public func retryResult(for request: Request, dueTo error: Error, completion: @escaping (RetryResult) -> Void) {
  840. guard let retrier = retrier(for: request) else {
  841. rootQueue.async { completion(.doNotRetry) }
  842. return
  843. }
  844. retrier.retry(request, for: self, dueTo: error) { retryResult in
  845. self.rootQueue.async {
  846. guard let retryResultError = retryResult.error else { completion(retryResult); return }
  847. let retryError = AFError.requestRetryFailed(retryError: retryResultError, originalError: error)
  848. completion(.doNotRetryWithError(retryError))
  849. }
  850. }
  851. }
  852. public func retryRequest(_ request: Request, withDelay timeDelay: TimeInterval?) {
  853. self.rootQueue.async {
  854. let retry: () -> Void = {
  855. guard !request.isCancelled else { return }
  856. request.prepareForRetry()
  857. self.perform(request)
  858. }
  859. if let retryDelay = timeDelay {
  860. self.rootQueue.after(retryDelay) { retry() }
  861. } else {
  862. retry()
  863. }
  864. }
  865. }
  866. }
  867. // MARK: - SessionStateProvider
  868. extension Session: SessionStateProvider {
  869. func request(for task: URLSessionTask) -> Request? {
  870. return requestTaskMap[task]
  871. }
  872. func didGatherMetricsForTask(_ task: URLSessionTask) {
  873. requestTaskMap.disassociateIfNecessaryAfterGatheringMetricsForTask(task)
  874. }
  875. func didCompleteTask(_ task: URLSessionTask) {
  876. requestTaskMap.disassociateIfNecessaryAfterCompletingTask(task)
  877. }
  878. func credential(for task: URLSessionTask, in protectionSpace: URLProtectionSpace) -> URLCredential? {
  879. return requestTaskMap[task]?.credential ??
  880. session.configuration.urlCredentialStorage?.defaultCredential(for: protectionSpace)
  881. }
  882. func cancelRequestsForSessionInvalidation(with error: Error?) {
  883. requestTaskMap.requests.forEach { $0.finish(error: AFError.sessionInvalidated(error: error)) }
  884. }
  885. }