Session.swift 70 KB

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