Session.swift 74 KB

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