Session.swift 70 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260
  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. let adapterState = RequestAdapterState(requestID: request.id, session: self)
  969. adapter.adapt(initialRequest, using: adapterState) { result in
  970. do {
  971. let adaptedRequest = try result.get()
  972. try adaptedRequest.validate()
  973. self.rootQueue.async { request.didAdaptInitialRequest(initialRequest, to: adaptedRequest) }
  974. guard shouldCreateTask() else { return }
  975. self.rootQueue.async { self.didCreateURLRequest(adaptedRequest, for: request) }
  976. } catch {
  977. self.rootQueue.async { request.didFailToAdaptURLRequest(initialRequest, withError: .requestAdaptationFailed(error: error)) }
  978. }
  979. }
  980. }
  981. // MARK: - Task Handling
  982. func didCreateURLRequest(_ urlRequest: URLRequest, for request: Request) {
  983. dispatchPrecondition(condition: .onQueue(rootQueue))
  984. request.didCreateURLRequest(urlRequest)
  985. guard !request.isCancelled else { return }
  986. let task = request.task(for: urlRequest, using: session)
  987. requestTaskMap[request] = task
  988. request.didCreateTask(task)
  989. updateStatesForTask(task, request: request)
  990. }
  991. func didReceiveResumeData(_ data: Data, for request: DownloadRequest) {
  992. dispatchPrecondition(condition: .onQueue(rootQueue))
  993. guard !request.isCancelled else { return }
  994. let task = request.task(forResumeData: data, using: session)
  995. requestTaskMap[request] = task
  996. request.didCreateTask(task)
  997. updateStatesForTask(task, request: request)
  998. }
  999. func updateStatesForTask(_ task: URLSessionTask, request: Request) {
  1000. dispatchPrecondition(condition: .onQueue(rootQueue))
  1001. request.withState { state in
  1002. switch state {
  1003. case .initialized, .finished:
  1004. // Do nothing.
  1005. break
  1006. case .resumed:
  1007. task.resume()
  1008. rootQueue.async { request.didResumeTask(task) }
  1009. case .suspended:
  1010. task.suspend()
  1011. rootQueue.async { request.didSuspendTask(task) }
  1012. case .cancelled:
  1013. // Resume to ensure metrics are gathered.
  1014. task.resume()
  1015. task.cancel()
  1016. rootQueue.async { request.didCancelTask(task) }
  1017. }
  1018. }
  1019. }
  1020. // MARK: - Adapters and Retriers
  1021. func adapter(for request: Request) -> RequestAdapter? {
  1022. if let requestInterceptor = request.interceptor, let sessionInterceptor = interceptor {
  1023. return Interceptor(adapters: [requestInterceptor, sessionInterceptor])
  1024. } else {
  1025. return request.interceptor ?? interceptor
  1026. }
  1027. }
  1028. func retrier(for request: Request) -> RequestRetrier? {
  1029. if let requestInterceptor = request.interceptor, let sessionInterceptor = interceptor {
  1030. return Interceptor(retriers: [requestInterceptor, sessionInterceptor])
  1031. } else {
  1032. return request.interceptor ?? interceptor
  1033. }
  1034. }
  1035. // MARK: - Invalidation
  1036. func finishRequestsForDeinit() {
  1037. requestTaskMap.requests.forEach { request in
  1038. rootQueue.async {
  1039. request.finish(error: AFError.sessionDeinitialized)
  1040. }
  1041. }
  1042. }
  1043. }
  1044. // MARK: - RequestDelegate
  1045. extension Session: RequestDelegate {
  1046. public var sessionConfiguration: URLSessionConfiguration {
  1047. session.configuration
  1048. }
  1049. public var startImmediately: Bool { startRequestsImmediately }
  1050. public func cleanup(after request: Request) {
  1051. activeRequests.remove(request)
  1052. }
  1053. public func retryResult(for request: Request, dueTo error: AFError, completion: @escaping (RetryResult) -> Void) {
  1054. guard let retrier = retrier(for: request) else {
  1055. rootQueue.async { completion(.doNotRetry) }
  1056. return
  1057. }
  1058. retrier.retry(request, for: self, dueTo: error) { retryResult in
  1059. self.rootQueue.async {
  1060. guard let retryResultError = retryResult.error else { completion(retryResult); return }
  1061. let retryError = AFError.requestRetryFailed(retryError: retryResultError, originalError: error)
  1062. completion(.doNotRetryWithError(retryError))
  1063. }
  1064. }
  1065. }
  1066. public func retryRequest(_ request: Request, withDelay timeDelay: TimeInterval?) {
  1067. rootQueue.async {
  1068. let retry: () -> Void = {
  1069. guard !request.isCancelled else { return }
  1070. request.prepareForRetry()
  1071. self.perform(request)
  1072. }
  1073. if let retryDelay = timeDelay {
  1074. self.rootQueue.after(retryDelay) { retry() }
  1075. } else {
  1076. retry()
  1077. }
  1078. }
  1079. }
  1080. }
  1081. // MARK: - SessionStateProvider
  1082. extension Session: SessionStateProvider {
  1083. func request(for task: URLSessionTask) -> Request? {
  1084. dispatchPrecondition(condition: .onQueue(rootQueue))
  1085. return requestTaskMap[task]
  1086. }
  1087. func didGatherMetricsForTask(_ task: URLSessionTask) {
  1088. dispatchPrecondition(condition: .onQueue(rootQueue))
  1089. let didDisassociate = requestTaskMap.disassociateIfNecessaryAfterGatheringMetricsForTask(task)
  1090. if didDisassociate {
  1091. waitingCompletions[task]?()
  1092. waitingCompletions[task] = nil
  1093. }
  1094. }
  1095. func didCompleteTask(_ task: URLSessionTask, completion: @escaping () -> Void) {
  1096. dispatchPrecondition(condition: .onQueue(rootQueue))
  1097. let didDisassociate = requestTaskMap.disassociateIfNecessaryAfterCompletingTask(task)
  1098. if didDisassociate {
  1099. completion()
  1100. } else {
  1101. waitingCompletions[task] = completion
  1102. }
  1103. }
  1104. func credential(for task: URLSessionTask, in protectionSpace: URLProtectionSpace) -> URLCredential? {
  1105. dispatchPrecondition(condition: .onQueue(rootQueue))
  1106. return requestTaskMap[task]?.credential ??
  1107. session.configuration.urlCredentialStorage?.defaultCredential(for: protectionSpace)
  1108. }
  1109. func cancelRequestsForSessionInvalidation(with error: Error?) {
  1110. dispatchPrecondition(condition: .onQueue(rootQueue))
  1111. requestTaskMap.requests.forEach { $0.finish(error: AFError.sessionInvalidated(error: error)) }
  1112. }
  1113. }