Session.swift 69 KB

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