Session.swift 68 KB

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