Session.swift 70 KB

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