Session.swift 70 KB

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