Session.swift 69 KB

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