Session.swift 70 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262
  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. /// - requestModifier: `RequestModifier` which will be applied to the `URLRequest` created from
  299. /// the provided parameters. `nil` by default.
  300. ///
  301. /// - Returns: The created `DataRequest`.
  302. open func request<Parameters: Encodable>(_ convertible: URLConvertible,
  303. method: HTTPMethod = .get,
  304. parameters: Parameters? = nil,
  305. encoder: ParameterEncoder = URLEncodedFormParameterEncoder.default,
  306. headers: HTTPHeaders? = nil,
  307. interceptor: RequestInterceptor? = nil,
  308. requestModifier: RequestModifier? = nil) -> DataRequest {
  309. let convertible = RequestEncodableConvertible(url: convertible,
  310. method: method,
  311. parameters: parameters,
  312. encoder: encoder,
  313. headers: headers,
  314. requestModifier: requestModifier)
  315. return request(convertible, interceptor: interceptor)
  316. }
  317. /// Creates a `DataRequest` from a `URLRequestConvertible` value and a `RequestInterceptor`.
  318. ///
  319. /// - Parameters:
  320. /// - convertible: `URLRequestConvertible` value to be used to create the `URLRequest`.
  321. /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
  322. ///
  323. /// - Returns: The created `DataRequest`.
  324. open func request(_ convertible: URLRequestConvertible, interceptor: RequestInterceptor? = nil) -> DataRequest {
  325. let request = DataRequest(convertible: convertible,
  326. underlyingQueue: rootQueue,
  327. serializationQueue: serializationQueue,
  328. eventMonitor: eventMonitor,
  329. interceptor: interceptor,
  330. delegate: self)
  331. perform(request)
  332. return request
  333. }
  334. // MARK: - DataStreamRequest
  335. /// Creates a `DataStreamRequest` from the passed components, `Encodable` parameters, and `RequestInterceptor`.
  336. ///
  337. /// - Parameters:
  338. /// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`.
  339. /// - method: `HTTPMethod` for the `URLRequest`. `.get` by default.
  340. /// - parameters: `Encodable` value to be encoded into the `URLRequest`. `nil` by default.
  341. /// - encoder: `ParameterEncoder` to be used to encode the `parameters` value into the
  342. /// `URLRequest`.
  343. /// `URLEncodedFormParameterEncoder.default` by default.
  344. /// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default.
  345. /// - automaticallyCancelOnStreamError: `Bool` indicating whether the instance should be canceled when an `Error`
  346. /// is thrown while serializing stream `Data`. `false` by default.
  347. /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil`
  348. /// by default.
  349. /// - requestModifier: `RequestModifier` which will be applied to the `URLRequest` created from
  350. /// the provided parameters. `nil` by default.
  351. ///
  352. /// - Returns: The created `DataStream` request.
  353. open func streamRequest<Parameters: Encodable>(_ convertible: URLConvertible,
  354. method: HTTPMethod = .get,
  355. parameters: Parameters? = nil,
  356. encoder: ParameterEncoder = URLEncodedFormParameterEncoder.default,
  357. headers: HTTPHeaders? = nil,
  358. automaticallyCancelOnStreamError: Bool = false,
  359. interceptor: RequestInterceptor? = nil,
  360. requestModifier: RequestModifier? = nil) -> DataStreamRequest {
  361. let convertible = RequestEncodableConvertible(url: convertible,
  362. method: method,
  363. parameters: parameters,
  364. encoder: encoder,
  365. headers: headers,
  366. requestModifier: requestModifier)
  367. return streamRequest(convertible,
  368. automaticallyCancelOnStreamError: automaticallyCancelOnStreamError,
  369. interceptor: interceptor)
  370. }
  371. /// Creates a `DataStreamRequest` from the passed components and `RequestInterceptor`.
  372. ///
  373. /// - Parameters:
  374. /// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`.
  375. /// - method: `HTTPMethod` for the `URLRequest`. `.get` by default.
  376. /// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default.
  377. /// - automaticallyCancelOnStreamError: `Bool` indicating whether the instance should be canceled when an `Error`
  378. /// is thrown while serializing stream `Data`. `false` by default.
  379. /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil`
  380. /// by default.
  381. /// - requestModifier: `RequestModifier` which will be applied to the `URLRequest` created from
  382. /// the provided parameters. `nil` by default.
  383. ///
  384. /// - Returns: The created `DataStream` request.
  385. open func streamRequest(_ convertible: URLConvertible,
  386. method: HTTPMethod = .get,
  387. headers: HTTPHeaders? = nil,
  388. automaticallyCancelOnStreamError: Bool = false,
  389. interceptor: RequestInterceptor? = nil,
  390. requestModifier: RequestModifier? = nil) -> DataStreamRequest {
  391. let convertible = RequestEncodableConvertible(url: convertible,
  392. method: method,
  393. parameters: Empty?.none,
  394. encoder: URLEncodedFormParameterEncoder.default,
  395. headers: headers,
  396. requestModifier: requestModifier)
  397. return streamRequest(convertible,
  398. automaticallyCancelOnStreamError: automaticallyCancelOnStreamError,
  399. interceptor: interceptor)
  400. }
  401. /// Creates a `DataStreamRequest` from the passed `URLRequestConvertible` value and `RequestInterceptor`.
  402. ///
  403. /// - Parameters:
  404. /// - convertible: `URLRequestConvertible` value to be used to create the `URLRequest`.
  405. /// - automaticallyCancelOnStreamError: `Bool` indicating whether the instance should be canceled when an `Error`
  406. /// is thrown while serializing stream `Data`. `false` by default.
  407. /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil`
  408. /// by default.
  409. ///
  410. /// - Returns: The created `DataStreamRequest`.
  411. open func streamRequest(_ convertible: URLRequestConvertible,
  412. automaticallyCancelOnStreamError: Bool = false,
  413. interceptor: RequestInterceptor? = nil) -> DataStreamRequest {
  414. let request = DataStreamRequest(convertible: convertible,
  415. automaticallyCancelOnStreamError: automaticallyCancelOnStreamError,
  416. underlyingQueue: rootQueue,
  417. serializationQueue: serializationQueue,
  418. eventMonitor: eventMonitor,
  419. interceptor: interceptor,
  420. delegate: self)
  421. perform(request)
  422. return request
  423. }
  424. // MARK: - DownloadRequest
  425. /// Creates a `DownloadRequest` using a `URLRequest` created using the passed components, `RequestInterceptor`, and
  426. /// `Destination`.
  427. ///
  428. /// - Parameters:
  429. /// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`.
  430. /// - method: `HTTPMethod` for the `URLRequest`. `.get` by default.
  431. /// - parameters: `Parameters` (a.k.a. `[String: Any]`) value to be encoded into the `URLRequest`. `nil` by
  432. /// default.
  433. /// - encoding: `ParameterEncoding` to be used to encode the `parameters` value into the `URLRequest`.
  434. /// Defaults to `URLEncoding.default`.
  435. /// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default.
  436. /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
  437. /// - requestModifier: `RequestModifier` which will be applied to the `URLRequest` created from the provided
  438. /// parameters. `nil` by default.
  439. /// - destination: `DownloadRequest.Destination` closure used to determine how and where the downloaded file
  440. /// should be moved. `nil` by default.
  441. ///
  442. /// - Returns: The created `DownloadRequest`.
  443. open func download(_ convertible: URLConvertible,
  444. method: HTTPMethod = .get,
  445. parameters: Parameters? = nil,
  446. encoding: ParameterEncoding = URLEncoding.default,
  447. headers: HTTPHeaders? = nil,
  448. interceptor: RequestInterceptor? = nil,
  449. requestModifier: RequestModifier? = nil,
  450. to destination: DownloadRequest.Destination? = nil) -> DownloadRequest {
  451. let convertible = RequestConvertible(url: convertible,
  452. method: method,
  453. parameters: parameters,
  454. encoding: encoding,
  455. headers: headers,
  456. requestModifier: requestModifier)
  457. return download(convertible, interceptor: interceptor, to: destination)
  458. }
  459. /// Creates a `DownloadRequest` from a `URLRequest` created using the passed components, `Encodable` parameters, and
  460. /// a `RequestInterceptor`.
  461. ///
  462. /// - Parameters:
  463. /// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`.
  464. /// - method: `HTTPMethod` for the `URLRequest`. `.get` by default.
  465. /// - parameters: Value conforming to `Encodable` to be encoded into the `URLRequest`. `nil` by default.
  466. /// - encoder: `ParameterEncoder` to be used to encode the `parameters` value into the `URLRequest`.
  467. /// Defaults to `URLEncodedFormParameterEncoder.default`.
  468. /// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default.
  469. /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
  470. /// - requestModifier: `RequestModifier` which will be applied to the `URLRequest` created from the provided
  471. /// parameters. `nil` by default.
  472. /// - destination: `DownloadRequest.Destination` closure used to determine how and where the downloaded file
  473. /// should be moved. `nil` by default.
  474. ///
  475. /// - Returns: The created `DownloadRequest`.
  476. open func download<Parameters: Encodable>(_ convertible: URLConvertible,
  477. method: HTTPMethod = .get,
  478. parameters: Parameters? = nil,
  479. encoder: ParameterEncoder = URLEncodedFormParameterEncoder.default,
  480. headers: HTTPHeaders? = nil,
  481. interceptor: RequestInterceptor? = nil,
  482. requestModifier: RequestModifier? = nil,
  483. to destination: DownloadRequest.Destination? = nil) -> DownloadRequest {
  484. let convertible = RequestEncodableConvertible(url: convertible,
  485. method: method,
  486. parameters: parameters,
  487. encoder: encoder,
  488. headers: headers,
  489. requestModifier: requestModifier)
  490. return download(convertible, interceptor: interceptor, to: destination)
  491. }
  492. /// Creates a `DownloadRequest` from a `URLRequestConvertible` value, a `RequestInterceptor`, and a `Destination`.
  493. ///
  494. /// - Parameters:
  495. /// - convertible: `URLRequestConvertible` value to be used to create the `URLRequest`.
  496. /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
  497. /// - destination: `DownloadRequest.Destination` closure used to determine how and where the downloaded file
  498. /// should be moved. `nil` by default.
  499. ///
  500. /// - Returns: The created `DownloadRequest`.
  501. open func download(_ convertible: URLRequestConvertible,
  502. interceptor: RequestInterceptor? = nil,
  503. to destination: DownloadRequest.Destination? = nil) -> DownloadRequest {
  504. let request = DownloadRequest(downloadable: .request(convertible),
  505. underlyingQueue: rootQueue,
  506. serializationQueue: serializationQueue,
  507. eventMonitor: eventMonitor,
  508. interceptor: interceptor,
  509. delegate: self,
  510. destination: destination ?? DownloadRequest.defaultDestination)
  511. perform(request)
  512. return request
  513. }
  514. /// Creates a `DownloadRequest` from the `resumeData` produced from a previously cancelled `DownloadRequest`, as
  515. /// well as a `RequestInterceptor`, and a `Destination`.
  516. ///
  517. /// - Note: If `destination` is not specified, the download will be moved to a temporary location determined by
  518. /// Alamofire. The file will not be deleted until the system purges the temporary files.
  519. ///
  520. /// - 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),
  521. /// `resumeData` is broken on background URL session configurations. There's an underlying bug in the `resumeData`
  522. /// generation logic where the data is written incorrectly and will always fail to resume the download. For more
  523. /// information about the bug and possible workarounds, please refer to the [this Stack Overflow post](http://stackoverflow.com/a/39347461/1342462).
  524. ///
  525. /// - Parameters:
  526. /// - data: The resume data from a previously cancelled `DownloadRequest` or `URLSessionDownloadTask`.
  527. /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
  528. /// - destination: `DownloadRequest.Destination` closure used to determine how and where the downloaded file
  529. /// should be moved. `nil` by default.
  530. ///
  531. /// - Returns: The created `DownloadRequest`.
  532. open func download(resumingWith data: Data,
  533. interceptor: RequestInterceptor? = nil,
  534. to destination: DownloadRequest.Destination? = nil) -> DownloadRequest {
  535. let request = DownloadRequest(downloadable: .resumeData(data),
  536. underlyingQueue: rootQueue,
  537. serializationQueue: serializationQueue,
  538. eventMonitor: eventMonitor,
  539. interceptor: interceptor,
  540. delegate: self,
  541. destination: destination ?? DownloadRequest.defaultDestination)
  542. perform(request)
  543. return request
  544. }
  545. // MARK: - UploadRequest
  546. struct ParameterlessRequestConvertible: URLRequestConvertible {
  547. let url: URLConvertible
  548. let method: HTTPMethod
  549. let headers: HTTPHeaders?
  550. let requestModifier: RequestModifier?
  551. func asURLRequest() throws -> URLRequest {
  552. var request = try URLRequest(url: url, method: method, headers: headers)
  553. try requestModifier?(&request)
  554. return request
  555. }
  556. }
  557. struct Upload: UploadConvertible {
  558. let request: URLRequestConvertible
  559. let uploadable: UploadableConvertible
  560. func createUploadable() throws -> UploadRequest.Uploadable {
  561. try uploadable.createUploadable()
  562. }
  563. func asURLRequest() throws -> URLRequest {
  564. try request.asURLRequest()
  565. }
  566. }
  567. // MARK: Data
  568. /// Creates an `UploadRequest` for the given `Data`, `URLRequest` components, and `RequestInterceptor`.
  569. ///
  570. /// - Parameters:
  571. /// - data: The `Data` to upload.
  572. /// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`.
  573. /// - method: `HTTPMethod` for the `URLRequest`. `.post` by default.
  574. /// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default.
  575. /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
  576. /// - fileManager: `FileManager` instance to be used by the returned `UploadRequest`. `.default` instance by
  577. /// default.
  578. /// - requestModifier: `RequestModifier` which will be applied to the `URLRequest` created from the provided
  579. /// parameters. `nil` by default.
  580. ///
  581. /// - Returns: The created `UploadRequest`.
  582. open func upload(_ data: Data,
  583. to convertible: URLConvertible,
  584. method: HTTPMethod = .post,
  585. headers: HTTPHeaders? = nil,
  586. interceptor: RequestInterceptor? = nil,
  587. fileManager: FileManager = .default,
  588. requestModifier: RequestModifier? = nil) -> UploadRequest {
  589. let convertible = ParameterlessRequestConvertible(url: convertible,
  590. method: method,
  591. headers: headers,
  592. requestModifier: requestModifier)
  593. return upload(data, with: convertible, interceptor: interceptor, fileManager: fileManager)
  594. }
  595. /// Creates an `UploadRequest` for the given `Data` using the `URLRequestConvertible` value and `RequestInterceptor`.
  596. ///
  597. /// - Parameters:
  598. /// - data: The `Data` to upload.
  599. /// - convertible: `URLRequestConvertible` value to be used to create the `URLRequest`.
  600. /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
  601. /// - fileManager: `FileManager` instance to be used by the returned `UploadRequest`. `.default` instance by
  602. /// default.
  603. ///
  604. /// - Returns: The created `UploadRequest`.
  605. open func upload(_ data: Data,
  606. with convertible: URLRequestConvertible,
  607. interceptor: RequestInterceptor? = nil,
  608. fileManager: FileManager = .default) -> UploadRequest {
  609. upload(.data(data), with: convertible, interceptor: interceptor, fileManager: fileManager)
  610. }
  611. // MARK: File
  612. /// Creates an `UploadRequest` for the file at the given file `URL`, using a `URLRequest` from the provided
  613. /// components and `RequestInterceptor`.
  614. ///
  615. /// - Parameters:
  616. /// - fileURL: The `URL` of the file to upload.
  617. /// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`.
  618. /// - method: `HTTPMethod` for the `URLRequest`. `.post` by default.
  619. /// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default.
  620. /// - interceptor: `RequestInterceptor` value to be used by the returned `UploadRequest`. `nil` by default.
  621. /// - fileManager: `FileManager` instance to be used by the returned `UploadRequest`. `.default` instance by
  622. /// default.
  623. /// - requestModifier: `RequestModifier` which will be applied to the `URLRequest` created from the provided
  624. /// parameters. `nil` by default.
  625. ///
  626. /// - Returns: The created `UploadRequest`.
  627. open func upload(_ fileURL: URL,
  628. to convertible: URLConvertible,
  629. method: HTTPMethod = .post,
  630. headers: HTTPHeaders? = nil,
  631. interceptor: RequestInterceptor? = nil,
  632. fileManager: FileManager = .default,
  633. requestModifier: RequestModifier? = nil) -> UploadRequest {
  634. let convertible = ParameterlessRequestConvertible(url: convertible,
  635. method: method,
  636. headers: headers,
  637. requestModifier: requestModifier)
  638. return upload(fileURL, with: convertible, interceptor: interceptor, fileManager: fileManager)
  639. }
  640. /// Creates an `UploadRequest` for the file at the given file `URL` using the `URLRequestConvertible` value and
  641. /// `RequestInterceptor`.
  642. ///
  643. /// - Parameters:
  644. /// - fileURL: The `URL` of the file to upload.
  645. /// - convertible: `URLRequestConvertible` value to be used to create the `URLRequest`.
  646. /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
  647. /// - fileManager: `FileManager` instance to be used by the returned `UploadRequest`. `.default` instance by
  648. /// default.
  649. ///
  650. /// - Returns: The created `UploadRequest`.
  651. open func upload(_ fileURL: URL,
  652. with convertible: URLRequestConvertible,
  653. interceptor: RequestInterceptor? = nil,
  654. fileManager: FileManager = .default) -> UploadRequest {
  655. upload(.file(fileURL, shouldRemove: false), with: convertible, interceptor: interceptor, fileManager: fileManager)
  656. }
  657. // MARK: InputStream
  658. /// Creates an `UploadRequest` from the `InputStream` provided using a `URLRequest` from the provided components and
  659. /// `RequestInterceptor`.
  660. ///
  661. /// - Parameters:
  662. /// - stream: The `InputStream` that provides the data to upload.
  663. /// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`.
  664. /// - method: `HTTPMethod` for the `URLRequest`. `.post` by default.
  665. /// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default.
  666. /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
  667. /// - fileManager: `FileManager` instance to be used by the returned `UploadRequest`. `.default` instance by
  668. /// default.
  669. /// - requestModifier: `RequestModifier` which will be applied to the `URLRequest` created from the provided
  670. /// parameters. `nil` by default.
  671. ///
  672. /// - Returns: The created `UploadRequest`.
  673. open func upload(_ stream: InputStream,
  674. to convertible: URLConvertible,
  675. method: HTTPMethod = .post,
  676. headers: HTTPHeaders? = nil,
  677. interceptor: RequestInterceptor? = nil,
  678. fileManager: FileManager = .default,
  679. requestModifier: RequestModifier? = nil) -> UploadRequest {
  680. let convertible = ParameterlessRequestConvertible(url: convertible,
  681. method: method,
  682. headers: headers,
  683. requestModifier: requestModifier)
  684. return upload(stream, with: convertible, interceptor: interceptor, fileManager: fileManager)
  685. }
  686. /// Creates an `UploadRequest` from the provided `InputStream` using the `URLRequestConvertible` value and
  687. /// `RequestInterceptor`.
  688. ///
  689. /// - Parameters:
  690. /// - stream: The `InputStream` that provides the data to upload.
  691. /// - convertible: `URLRequestConvertible` value to be used to create the `URLRequest`.
  692. /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
  693. /// - fileManager: `FileManager` instance to be used by the returned `UploadRequest`. `.default` instance by
  694. /// default.
  695. ///
  696. /// - Returns: The created `UploadRequest`.
  697. open func upload(_ stream: InputStream,
  698. with convertible: URLRequestConvertible,
  699. interceptor: RequestInterceptor? = nil,
  700. fileManager: FileManager = .default) -> UploadRequest {
  701. upload(.stream(stream), with: convertible, interceptor: interceptor, fileManager: fileManager)
  702. }
  703. // MARK: MultipartFormData
  704. /// Creates an `UploadRequest` for the multipart form data built using a closure and sent using the provided
  705. /// `URLRequest` components and `RequestInterceptor`.
  706. ///
  707. /// It is important to understand the memory implications of uploading `MultipartFormData`. If the cumulative
  708. /// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most
  709. /// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to
  710. /// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory
  711. /// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be
  712. /// used for larger payloads such as video content.
  713. ///
  714. /// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory
  715. /// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`,
  716. /// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk
  717. /// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding
  718. /// technique was used.
  719. ///
  720. /// - Parameters:
  721. /// - multipartFormData: `MultipartFormData` building closure.
  722. /// - url: `URLConvertible` value to be used as the `URLRequest`'s `URL`.
  723. /// - encodingMemoryThreshold: Byte threshold used to determine whether the form data is encoded into memory or
  724. /// onto disk before being uploaded. `MultipartFormData.encodingMemoryThreshold` by
  725. /// default.
  726. /// - method: `HTTPMethod` for the `URLRequest`. `.post` by default.
  727. /// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default.
  728. /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
  729. /// - fileManager: `FileManager` to be used if the form data exceeds the memory threshold and is
  730. /// written to disk before being uploaded. `.default` instance by default.
  731. /// - requestModifier: `RequestModifier` which will be applied to the `URLRequest` created from the
  732. /// provided parameters. `nil` by default.
  733. ///
  734. /// - Returns: The created `UploadRequest`.
  735. open func upload(multipartFormData: @escaping (MultipartFormData) -> Void,
  736. to url: URLConvertible,
  737. usingThreshold encodingMemoryThreshold: UInt64 = MultipartFormData.encodingMemoryThreshold,
  738. method: HTTPMethod = .post,
  739. headers: HTTPHeaders? = nil,
  740. interceptor: RequestInterceptor? = nil,
  741. fileManager: FileManager = .default,
  742. requestModifier: RequestModifier? = nil) -> UploadRequest {
  743. let convertible = ParameterlessRequestConvertible(url: url,
  744. method: method,
  745. headers: headers,
  746. requestModifier: requestModifier)
  747. let formData = MultipartFormData(fileManager: fileManager)
  748. multipartFormData(formData)
  749. return upload(multipartFormData: formData,
  750. with: convertible,
  751. usingThreshold: encodingMemoryThreshold,
  752. interceptor: interceptor,
  753. fileManager: fileManager)
  754. }
  755. /// Creates an `UploadRequest` using a `MultipartFormData` building closure, the provided `URLRequestConvertible`
  756. /// value, and a `RequestInterceptor`.
  757. ///
  758. /// It is important to understand the memory implications of uploading `MultipartFormData`. If the cumulative
  759. /// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most
  760. /// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to
  761. /// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory
  762. /// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be
  763. /// used for larger payloads such as video content.
  764. ///
  765. /// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory
  766. /// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`,
  767. /// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk
  768. /// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding
  769. /// technique was used.
  770. ///
  771. /// - Parameters:
  772. /// - multipartFormData: `MultipartFormData` building closure.
  773. /// - request: `URLRequestConvertible` value to be used to create the `URLRequest`.
  774. /// - encodingMemoryThreshold: Byte threshold used to determine whether the form data is encoded into memory or
  775. /// onto disk before being uploaded. `MultipartFormData.encodingMemoryThreshold` by
  776. /// default.
  777. /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
  778. /// - fileManager: `FileManager` to be used if the form data exceeds the memory threshold and is
  779. /// written to disk before being uploaded. `.default` instance by default.
  780. ///
  781. /// - Returns: The created `UploadRequest`.
  782. open func upload(multipartFormData: @escaping (MultipartFormData) -> Void,
  783. with request: URLRequestConvertible,
  784. usingThreshold encodingMemoryThreshold: UInt64 = MultipartFormData.encodingMemoryThreshold,
  785. interceptor: RequestInterceptor? = nil,
  786. fileManager: FileManager = .default) -> UploadRequest {
  787. let formData = MultipartFormData(fileManager: fileManager)
  788. multipartFormData(formData)
  789. return upload(multipartFormData: formData,
  790. with: request,
  791. usingThreshold: encodingMemoryThreshold,
  792. interceptor: interceptor,
  793. fileManager: fileManager)
  794. }
  795. /// Creates an `UploadRequest` for the prebuilt `MultipartFormData` value using the provided `URLRequest` components
  796. /// and `RequestInterceptor`.
  797. ///
  798. /// It is important to understand the memory implications of uploading `MultipartFormData`. If the cumulative
  799. /// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most
  800. /// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to
  801. /// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory
  802. /// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be
  803. /// used for larger payloads such as video content.
  804. ///
  805. /// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory
  806. /// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`,
  807. /// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk
  808. /// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding
  809. /// technique was used.
  810. ///
  811. /// - Parameters:
  812. /// - multipartFormData: `MultipartFormData` instance to upload.
  813. /// - url: `URLConvertible` value to be used as the `URLRequest`'s `URL`.
  814. /// - encodingMemoryThreshold: Byte threshold used to determine whether the form data is encoded into memory or
  815. /// onto disk before being uploaded. `MultipartFormData.encodingMemoryThreshold` by
  816. /// default.
  817. /// - method: `HTTPMethod` for the `URLRequest`. `.post` by default.
  818. /// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default.
  819. /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
  820. /// - fileManager: `FileManager` to be used if the form data exceeds the memory threshold and is
  821. /// written to disk before being uploaded. `.default` instance by default.
  822. /// - requestModifier: `RequestModifier` which will be applied to the `URLRequest` created from the
  823. /// provided parameters. `nil` by default.
  824. ///
  825. /// - Returns: The created `UploadRequest`.
  826. open func upload(multipartFormData: MultipartFormData,
  827. to url: URLConvertible,
  828. usingThreshold encodingMemoryThreshold: UInt64 = MultipartFormData.encodingMemoryThreshold,
  829. method: HTTPMethod = .post,
  830. headers: HTTPHeaders? = nil,
  831. interceptor: RequestInterceptor? = nil,
  832. fileManager: FileManager = .default,
  833. requestModifier: RequestModifier? = nil) -> UploadRequest {
  834. let convertible = ParameterlessRequestConvertible(url: url,
  835. method: method,
  836. headers: headers,
  837. requestModifier: requestModifier)
  838. let multipartUpload = MultipartUpload(encodingMemoryThreshold: encodingMemoryThreshold,
  839. request: convertible,
  840. multipartFormData: multipartFormData)
  841. return upload(multipartUpload, interceptor: interceptor, fileManager: fileManager)
  842. }
  843. /// Creates an `UploadRequest` for the prebuilt `MultipartFormData` value using the providing `URLRequestConvertible`
  844. /// value and `RequestInterceptor`.
  845. ///
  846. /// It is important to understand the memory implications of uploading `MultipartFormData`. If the cumulative
  847. /// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most
  848. /// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to
  849. /// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory
  850. /// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be
  851. /// used for larger payloads such as video content.
  852. ///
  853. /// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory
  854. /// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`,
  855. /// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk
  856. /// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding
  857. /// technique was used.
  858. ///
  859. /// - Parameters:
  860. /// - multipartFormData: `MultipartFormData` instance to upload.
  861. /// - request: `URLRequestConvertible` value to be used to create the `URLRequest`.
  862. /// - encodingMemoryThreshold: Byte threshold used to determine whether the form data is encoded into memory or
  863. /// onto disk before being uploaded. `MultipartFormData.encodingMemoryThreshold` by
  864. /// default.
  865. /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
  866. /// - fileManager: `FileManager` instance to be used by the returned `UploadRequest`. `.default` instance by
  867. /// default.
  868. ///
  869. /// - Returns: The created `UploadRequest`.
  870. open func upload(multipartFormData: MultipartFormData,
  871. with request: URLRequestConvertible,
  872. usingThreshold encodingMemoryThreshold: UInt64 = MultipartFormData.encodingMemoryThreshold,
  873. interceptor: RequestInterceptor? = nil,
  874. fileManager: FileManager = .default) -> UploadRequest {
  875. let multipartUpload = MultipartUpload(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. performSetupOperations(for: request, convertible: request.convertible) {
  931. do {
  932. let uploadable = try request.upload.createUploadable()
  933. self.rootQueue.async { request.didCreateUploadable(uploadable) }
  934. return true
  935. } catch {
  936. self.rootQueue.async { request.didFailToCreateUploadable(with: error.asAFError(or: .createUploadableFailed(error: error))) }
  937. return false
  938. }
  939. }
  940. }
  941. func performDownloadRequest(_ request: DownloadRequest) {
  942. dispatchPrecondition(condition: .onQueue(requestQueue))
  943. switch request.downloadable {
  944. case let .request(convertible):
  945. performSetupOperations(for: request, convertible: convertible)
  946. case let .resumeData(resumeData):
  947. rootQueue.async { self.didReceiveResumeData(resumeData, for: request) }
  948. }
  949. }
  950. func performSetupOperations(for request: Request,
  951. convertible: URLRequestConvertible,
  952. shouldCreateTask: @escaping () -> Bool = { true })
  953. {
  954. dispatchPrecondition(condition: .onQueue(requestQueue))
  955. let initialRequest: URLRequest
  956. do {
  957. initialRequest = try convertible.asURLRequest()
  958. try initialRequest.validate()
  959. } catch {
  960. rootQueue.async { request.didFailToCreateURLRequest(with: error.asAFError(or: .createURLRequestFailed(error: error))) }
  961. return
  962. }
  963. rootQueue.async { request.didCreateInitialURLRequest(initialRequest) }
  964. guard !request.isCancelled else { return }
  965. guard let adapter = adapter(for: request) else {
  966. guard shouldCreateTask() else { return }
  967. rootQueue.async { self.didCreateURLRequest(initialRequest, for: request) }
  968. return
  969. }
  970. let adapterState = RequestAdapterState(requestID: request.id, session: self)
  971. adapter.adapt(initialRequest, using: adapterState) { result in
  972. do {
  973. let adaptedRequest = try result.get()
  974. try adaptedRequest.validate()
  975. self.rootQueue.async { request.didAdaptInitialRequest(initialRequest, to: adaptedRequest) }
  976. guard shouldCreateTask() else { return }
  977. self.rootQueue.async { self.didCreateURLRequest(adaptedRequest, for: request) }
  978. } catch {
  979. self.rootQueue.async { request.didFailToAdaptURLRequest(initialRequest, withError: .requestAdaptationFailed(error: error)) }
  980. }
  981. }
  982. }
  983. // MARK: - Task Handling
  984. func didCreateURLRequest(_ urlRequest: URLRequest, for request: Request) {
  985. dispatchPrecondition(condition: .onQueue(rootQueue))
  986. request.didCreateURLRequest(urlRequest)
  987. guard !request.isCancelled else { return }
  988. let task = request.task(for: urlRequest, using: session)
  989. requestTaskMap[request] = task
  990. request.didCreateTask(task)
  991. updateStatesForTask(task, request: request)
  992. }
  993. func didReceiveResumeData(_ data: Data, for request: DownloadRequest) {
  994. dispatchPrecondition(condition: .onQueue(rootQueue))
  995. guard !request.isCancelled else { return }
  996. let task = request.task(forResumeData: data, using: session)
  997. requestTaskMap[request] = task
  998. request.didCreateTask(task)
  999. updateStatesForTask(task, request: request)
  1000. }
  1001. func updateStatesForTask(_ task: URLSessionTask, request: Request) {
  1002. dispatchPrecondition(condition: .onQueue(rootQueue))
  1003. request.withState { state in
  1004. switch state {
  1005. case .initialized, .finished:
  1006. // Do nothing.
  1007. break
  1008. case .resumed:
  1009. task.resume()
  1010. rootQueue.async { request.didResumeTask(task) }
  1011. case .suspended:
  1012. task.suspend()
  1013. rootQueue.async { request.didSuspendTask(task) }
  1014. case .cancelled:
  1015. // Resume to ensure metrics are gathered.
  1016. task.resume()
  1017. task.cancel()
  1018. rootQueue.async { request.didCancelTask(task) }
  1019. }
  1020. }
  1021. }
  1022. // MARK: - Adapters and Retriers
  1023. func adapter(for request: Request) -> RequestAdapter? {
  1024. if let requestInterceptor = request.interceptor, let sessionInterceptor = interceptor {
  1025. return Interceptor(adapters: [requestInterceptor, sessionInterceptor])
  1026. } else {
  1027. return request.interceptor ?? interceptor
  1028. }
  1029. }
  1030. func retrier(for request: Request) -> RequestRetrier? {
  1031. if let requestInterceptor = request.interceptor, let sessionInterceptor = interceptor {
  1032. return Interceptor(retriers: [requestInterceptor, sessionInterceptor])
  1033. } else {
  1034. return request.interceptor ?? interceptor
  1035. }
  1036. }
  1037. // MARK: - Invalidation
  1038. func finishRequestsForDeinit() {
  1039. requestTaskMap.requests.forEach { request in
  1040. rootQueue.async {
  1041. request.finish(error: AFError.sessionDeinitialized)
  1042. }
  1043. }
  1044. }
  1045. }
  1046. // MARK: - RequestDelegate
  1047. extension Session: RequestDelegate {
  1048. public var sessionConfiguration: URLSessionConfiguration {
  1049. session.configuration
  1050. }
  1051. public var startImmediately: Bool { startRequestsImmediately }
  1052. public func cleanup(after request: Request) {
  1053. activeRequests.remove(request)
  1054. }
  1055. public func retryResult(for request: Request, dueTo error: AFError, completion: @escaping (RetryResult) -> Void) {
  1056. guard let retrier = retrier(for: request) else {
  1057. rootQueue.async { completion(.doNotRetry) }
  1058. return
  1059. }
  1060. retrier.retry(request, for: self, dueTo: error) { retryResult in
  1061. self.rootQueue.async {
  1062. guard let retryResultError = retryResult.error else { completion(retryResult); return }
  1063. let retryError = AFError.requestRetryFailed(retryError: retryResultError, originalError: error)
  1064. completion(.doNotRetryWithError(retryError))
  1065. }
  1066. }
  1067. }
  1068. public func retryRequest(_ request: Request, withDelay timeDelay: TimeInterval?) {
  1069. rootQueue.async {
  1070. let retry: () -> Void = {
  1071. guard !request.isCancelled else { return }
  1072. request.prepareForRetry()
  1073. self.perform(request)
  1074. }
  1075. if let retryDelay = timeDelay {
  1076. self.rootQueue.after(retryDelay) { retry() }
  1077. } else {
  1078. retry()
  1079. }
  1080. }
  1081. }
  1082. }
  1083. // MARK: - SessionStateProvider
  1084. extension Session: SessionStateProvider {
  1085. func request(for task: URLSessionTask) -> Request? {
  1086. dispatchPrecondition(condition: .onQueue(rootQueue))
  1087. return requestTaskMap[task]
  1088. }
  1089. func didGatherMetricsForTask(_ task: URLSessionTask) {
  1090. dispatchPrecondition(condition: .onQueue(rootQueue))
  1091. let didDisassociate = requestTaskMap.disassociateIfNecessaryAfterGatheringMetricsForTask(task)
  1092. if didDisassociate {
  1093. waitingCompletions[task]?()
  1094. waitingCompletions[task] = nil
  1095. }
  1096. }
  1097. func didCompleteTask(_ task: URLSessionTask, completion: @escaping () -> Void) {
  1098. dispatchPrecondition(condition: .onQueue(rootQueue))
  1099. let didDisassociate = requestTaskMap.disassociateIfNecessaryAfterCompletingTask(task)
  1100. if didDisassociate {
  1101. completion()
  1102. } else {
  1103. waitingCompletions[task] = completion
  1104. }
  1105. }
  1106. func credential(for task: URLSessionTask, in protectionSpace: URLProtectionSpace) -> URLCredential? {
  1107. dispatchPrecondition(condition: .onQueue(rootQueue))
  1108. return requestTaskMap[task]?.credential ??
  1109. session.configuration.urlCredentialStorage?.defaultCredential(for: protectionSpace)
  1110. }
  1111. func cancelRequestsForSessionInvalidation(with error: Error?) {
  1112. dispatchPrecondition(condition: .onQueue(rootQueue))
  1113. requestTaskMap.requests.forEach { $0.finish(error: AFError.sessionInvalidated(error: error)) }
  1114. }
  1115. }