Session.swift 75 KB

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