| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062 |
- //
- // Session.swift
- //
- // Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/)
- //
- // Permission is hereby granted, free of charge, to any person obtaining a copy
- // of this software and associated documentation files (the "Software"), to deal
- // in the Software without restriction, including without limitation the rights
- // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- // copies of the Software, and to permit persons to whom the Software is
- // furnished to do so, subject to the following conditions:
- //
- // The above copyright notice and this permission notice shall be included in
- // all copies or substantial portions of the Software.
- //
- // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- // THE SOFTWARE.
- //
- import Foundation
- /// `Session` creates and manages Alamofire's `Request` types during their lifetimes. It also provides common
- /// functionality for all `Request`s, including queuing, interception, trust management, redirect handling, and response
- /// cache handling.
- open class Session {
- /// Shared singleton instance used by all `AF.request` APIs. Cannot be modified.
- public static let `default` = Session()
- /// Underlying `URLSession` used to create `URLSessionTasks` for this instance, and for which this instance's
- /// `delegate` handles `URLSessionDelegate` callbacks.
- public let session: URLSession
- /// Instance's `SessionDelegate`, which handles the `URLSessionDelegate` methods and `Request` interaction.
- public let delegate: SessionDelegate
- /// Root `DispatchQueue` for all internal callbacks and state update. **MUST** be a serial queue.
- public let rootQueue: DispatchQueue
- /// Value determining whether this instance automatically calls `resume()` on all created `Request`s.
- public let startRequestsImmediately: Bool
- /// `DispatchQueue` on which `URLRequest`s are created asynchronously. By default this queue uses `rootQueue` as its
- /// `target`, but a separate queue can be used if request creation is determined to be a bottleneck. Always profile
- /// and test before introducing an additional queue.
- public let requestQueue: DispatchQueue
- /// `DispatchQueue` passed to all `Request`s on which they perform their response serialization. By default this
- /// queue uses `rootQueue` as its `target` but a separate queue can be used if response serialization is determined
- /// to be a bottleneck. Always profile and test before introducing an additional queue.
- public let serializationQueue: DispatchQueue
- /// `RequestInterceptor` used for all `Request` created by the instance. `RequestInterceptor`s can also be set on a
- /// per-`Request` basis, in which case the `Request`'s interceptor takes precedence over this value.
- public let interceptor: RequestInterceptor?
- /// `ServerTrustManager` instance used to evaluate all trust challenges and provide certificate and key pinning.
- public let serverTrustManager: ServerTrustManager?
- /// `RedirectHandler` instance used to provide customization for request redirection.
- public let redirectHandler: RedirectHandler?
- /// `CachedResponseHandler` instance used to provide customization of cached response handling.
- public let cachedResponseHandler: CachedResponseHandler?
- /// `CompositeEventMonitor` used to compose Alamofire's `defaultEventMonitors` and any passed `EventMonitor`s.
- public let eventMonitor: CompositeEventMonitor
- /// `EventMonitor`s included in all instances. `[AlamofireNotifications()]` by default.
- public let defaultEventMonitors: [EventMonitor] = [AlamofireNotifications()]
- /// Internal map between `Request`s and any `URLSessionTasks` that may be in flight for them.
- var requestTaskMap = RequestTaskMap()
- /// Set of currently active `Request`s.
- var activeRequests: Set<Request> = []
- /// Completion events awaiting `URLSessionTaskMetrics`.
- var waitingCompletions: [URLSessionTask: () -> Void] = [:]
- /// Creates a `Session` from a `URLSession` and other parameters.
- ///
- /// - Note: When passing a `URLSession`, you must create the `URLSession` with a specific `delegateQueue` value and
- /// pass the `delegateQueue`'s `underlyingQueue` as the `rootQueue` parameter of this initializer.
- ///
- /// - Parameters:
- /// - session: Underlying `URLSession` for this instance.
- /// - delegate: `SessionDelegate` that handles `session`'s delegate callbacks as well as `Request`
- /// interaction.
- /// - rootQueue: Root `DispatchQueue` for all internal callbacks and state updates. **MUST** be a
- /// serial queue.
- /// - startRequestsImmediately: Determines whether this instance will automatically start all `Request`s. `true`
- /// by default. If set to `false`, all `Request`s created must have `.resume()` called.
- /// on them for them to start.
- /// - requestQueue: `DispatchQueue` on which to perform `URLRequest` creation. By default this queue
- /// will use the `rootQueue` as its `target`. A separate queue can be used if it's
- /// determined request creation is a bottleneck, but that should only be done after
- /// careful testing and profiling. `nil` by default.
- /// - serializationQueue: `DispatchQueue` on which to perform all response serialization. By default this
- /// queue will use the `rootQueue` as its `target`. A separate queue can be used if
- /// it's determined response serialization is a bottleneck, but that should only be
- /// done after careful testing and profiling. `nil` by default.
- /// - interceptor: `RequestInterceptor` to be used for all `Request`s created by this instance. `nil`
- /// by default.
- /// - serverTrustManager: `ServerTrustManager` to be used for all trust evaluations by this instance. `nil`
- /// by default.
- /// - redirectHandler: `RedirectHandler` to be used by all `Request`s created by this instance. `nil` by
- /// default.
- /// - cachedResponseHandler: `CachedResponseHandler` to be used by all `Request`s created by this instance.
- /// `nil` by default.
- /// - eventMonitors: Additional `EventMonitor`s used by the instance. Alamofire always adds a
- /// `AlamofireNotifications` `EventMonitor` to the array passed here. `[]` by default.
- public init(session: URLSession,
- delegate: SessionDelegate,
- rootQueue: DispatchQueue,
- startRequestsImmediately: Bool = true,
- requestQueue: DispatchQueue? = nil,
- serializationQueue: DispatchQueue? = nil,
- interceptor: RequestInterceptor? = nil,
- serverTrustManager: ServerTrustManager? = nil,
- redirectHandler: RedirectHandler? = nil,
- cachedResponseHandler: CachedResponseHandler? = nil,
- eventMonitors: [EventMonitor] = []) {
- precondition(session.configuration.identifier == nil,
- "Alamofire does not support background URLSessionConfigurations.")
- precondition(session.delegateQueue.underlyingQueue === rootQueue,
- "Session(session:) initializer must be passed the DispatchQueue used as the delegateQueue's underlyingQueue as rootQueue.")
- self.session = session
- self.delegate = delegate
- self.rootQueue = rootQueue
- self.startRequestsImmediately = startRequestsImmediately
- self.requestQueue = requestQueue ?? DispatchQueue(label: "\(rootQueue.label).requestQueue", target: rootQueue)
- self.serializationQueue = serializationQueue ?? DispatchQueue(label: "\(rootQueue.label).serializationQueue", target: rootQueue)
- self.interceptor = interceptor
- self.serverTrustManager = serverTrustManager
- self.redirectHandler = redirectHandler
- self.cachedResponseHandler = cachedResponseHandler
- eventMonitor = CompositeEventMonitor(monitors: defaultEventMonitors + eventMonitors)
- delegate.eventMonitor = eventMonitor
- delegate.stateProvider = self
- }
- /// Creates a `Session` from a `URLSessionConfiguration`.
- ///
- /// - Note: This initializer lets Alamofire handle the creation of the underlying `URLSession` and its
- /// `delegateQueue`, and is the recommended initializer for most uses.
- ///
- /// - Parameters:
- /// - configuration: `URLSessionConfiguration` to be used to create the underlying `URLSession`. Changes
- /// to this value after being passed to this initializer will have no effect.
- /// `URLSessionConfiguration.af.default` by default.
- /// - delegate: `SessionDelegate` that handles `session`'s delegate callbacks as well as `Request`
- /// interaction. `SessionDelegate()` by default.
- /// - rootQueue: Root `DispatchQueue` for all internal callbacks and state updates. **MUST** be a
- /// serial queue. `DispatchQueue(label: "org.alamofire.session.rootQueue")` by default.
- /// - startRequestsImmediately: Determines whether this instance will automatically start all `Request`s. `true`
- /// by default. If set to `false`, all `Request`s created must have `.resume()` called.
- /// on them for them to start.
- /// - requestQueue: `DispatchQueue` on which to perform `URLRequest` creation. By default this queue
- /// will use the `rootQueue` as its `target`. A separate queue can be used if it's
- /// determined request creation is a bottleneck, but that should only be done after
- /// careful testing and profiling. `nil` by default.
- /// - serializationQueue: `DispatchQueue` on which to perform all response serialization. By default this
- /// queue will use the `rootQueue` as its `target`. A separate queue can be used if
- /// it's determined response serialization is a bottleneck, but that should only be
- /// done after careful testing and profiling. `nil` by default.
- /// - interceptor: `RequestInterceptor` to be used for all `Request`s created by this instance. `nil`
- /// by default.
- /// - serverTrustManager: `ServerTrustManager` to be used for all trust evaluations by this instance. `nil`
- /// by default.
- /// - redirectHandler: `RedirectHandler` to be used by all `Request`s created by this instance. `nil` by
- /// default.
- /// - cachedResponseHandler: `CachedResponseHandler` to be used by all `Request`s created by this instance.
- /// `nil` by default.
- /// - eventMonitors: Additional `EventMonitor`s used by the instance. Alamofire always adds a
- /// `AlamofireNotifications` `EventMonitor` to the array passed here. `[]` by default.
- public convenience init(configuration: URLSessionConfiguration = URLSessionConfiguration.af.default,
- delegate: SessionDelegate = SessionDelegate(),
- rootQueue: DispatchQueue = DispatchQueue(label: "org.alamofire.session.rootQueue"),
- startRequestsImmediately: Bool = true,
- requestQueue: DispatchQueue? = nil,
- serializationQueue: DispatchQueue? = nil,
- interceptor: RequestInterceptor? = nil,
- serverTrustManager: ServerTrustManager? = nil,
- redirectHandler: RedirectHandler? = nil,
- cachedResponseHandler: CachedResponseHandler? = nil,
- eventMonitors: [EventMonitor] = []) {
- precondition(configuration.identifier == nil, "Alamofire does not support background URLSessionConfigurations.")
- let delegateQueue = OperationQueue(maxConcurrentOperationCount: 1, underlyingQueue: rootQueue, name: "org.alamofire.session.sessionDelegateQueue")
- let session = URLSession(configuration: configuration, delegate: delegate, delegateQueue: delegateQueue)
- self.init(session: session,
- delegate: delegate,
- rootQueue: rootQueue,
- startRequestsImmediately: startRequestsImmediately,
- requestQueue: requestQueue,
- serializationQueue: serializationQueue,
- interceptor: interceptor,
- serverTrustManager: serverTrustManager,
- redirectHandler: redirectHandler,
- cachedResponseHandler: cachedResponseHandler,
- eventMonitors: eventMonitors)
- }
- deinit {
- finishRequestsForDeinit()
- session.invalidateAndCancel()
- }
- // MARK: - Cancellation
- /// Cancel all active `Request`s, optionally calling a completion handler when complete.
- ///
- /// - Note: This is an asynchronous operation and does not block the creation of future `Request`s. Cancelled
- /// `Request`s may not cancel immediately due internal work, and may not cancel at all if they are close to
- /// completion when cancelled.
- ///
- /// - Parameters:
- /// - queue: `DispatchQueue` on which the completion handler is run. `.main` by default.
- /// - completion: Closure to be called when all `Request`s have been cancelled.
- public func cancelAllRequests(completingOnQueue queue: DispatchQueue = .main, completion: (() -> Void)? = nil) {
- rootQueue.async {
- self.activeRequests.forEach { $0.cancel() }
- queue.async { completion?() }
- }
- }
- // MARK: - DataRequest
- struct RequestConvertible: URLRequestConvertible {
- let url: URLConvertible
- let method: HTTPMethod
- let parameters: Parameters?
- let encoding: ParameterEncoding
- let headers: HTTPHeaders?
- func asURLRequest() throws -> URLRequest {
- let request = try URLRequest(url: url, method: method, headers: headers)
- return try encoding.encode(request, with: parameters)
- }
- }
- /// Creates a `DataRequest` from a `URLRequest` created using the passed components and a `RequestInterceptor`.
- ///
- /// - Parameters:
- /// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`.
- /// - method: `HTTPMethod` for the `URLRequest`. `.get` by default.
- /// - parameters: `Parameters` (a.k.a. `[String: Any]`) value to be encoded into the `URLRequest`. `nil` by default.
- /// - encoding: `ParameterEncoding` to be used to encode the `parameters` value into the `URLRequest`.
- /// `URLEncoding.default` by default.
- /// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default.
- /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
- ///
- /// - Returns: The created `DataRequest`.
- open func request(_ convertible: URLConvertible,
- method: HTTPMethod = .get,
- parameters: Parameters? = nil,
- encoding: ParameterEncoding = URLEncoding.default,
- headers: HTTPHeaders? = nil,
- interceptor: RequestInterceptor? = nil) -> DataRequest {
- let convertible = RequestConvertible(url: convertible,
- method: method,
- parameters: parameters,
- encoding: encoding,
- headers: headers)
- return request(convertible, interceptor: interceptor)
- }
- struct RequestEncodableConvertible<Parameters: Encodable>: URLRequestConvertible {
- let url: URLConvertible
- let method: HTTPMethod
- let parameters: Parameters?
- let encoder: ParameterEncoder
- let headers: HTTPHeaders?
- func asURLRequest() throws -> URLRequest {
- let request = try URLRequest(url: url, method: method, headers: headers)
- return try parameters.map { try encoder.encode($0, into: request) } ?? request
- }
- }
- /// Creates a `DataRequest` from a `URLRequest` created using the passed components, `Encodable` parameters, and a
- /// `RequestInterceptor`.
- ///
- /// - Parameters:
- /// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`.
- /// - method: `HTTPMethod` for the `URLRequest`. `.get` by default.
- /// - parameters: `Encodable` value to be encoded into the `URLRequest`. `nil` by default.
- /// - encoder: `ParameterEncoder` to be used to encode the `parameters` value into the `URLRequest`.
- /// `URLEncodedFormParameterEncoder.default` by default.
- /// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default.
- /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
- ///
- /// - Returns: The created `DataRequest`.
- open func request<Parameters: Encodable>(_ convertible: URLConvertible,
- method: HTTPMethod = .get,
- parameters: Parameters? = nil,
- encoder: ParameterEncoder = URLEncodedFormParameterEncoder.default,
- headers: HTTPHeaders? = nil,
- interceptor: RequestInterceptor? = nil) -> DataRequest {
- let convertible = RequestEncodableConvertible(url: convertible,
- method: method,
- parameters: parameters,
- encoder: encoder,
- headers: headers)
- return request(convertible, interceptor: interceptor)
- }
- /// Creates a `DataRequest` from a `URLRequestConvertible` value and a `RequestInterceptor`.
- ///
- /// - Parameters:
- /// - convertible: `URLRequestConvertible` value to be used to create the `URLRequest`.
- /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
- ///
- /// - Returns: The created `DataRequest`.
- open func request(_ convertible: URLRequestConvertible, interceptor: RequestInterceptor? = nil) -> DataRequest {
- let request = DataRequest(convertible: convertible,
- underlyingQueue: rootQueue,
- serializationQueue: serializationQueue,
- eventMonitor: eventMonitor,
- interceptor: interceptor,
- delegate: self)
- perform(request)
- return request
- }
- // MARK: - DownloadRequest
- /// Creates a `DownloadRequest` using a `URLRequest` created using the passed components, `RequestInterceptor`, and
- /// `Destination`.
- ///
- /// - Parameters:
- /// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`.
- /// - method: `HTTPMethod` for the `URLRequest`. `.get` by default.
- /// - parameters: `Parameters` (a.k.a. `[String: Any]`) value to be encoded into the `URLRequest`. `nil` by default.
- /// - encoding: `ParameterEncoding` to be used to encode the `parameters` value into the `URLRequest`. Defaults
- /// to `URLEncoding.default`.
- /// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default.
- /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
- /// - destination: `DownloadRequest.Destination` closure used to determine how and where the downloaded file
- /// should be moved. `nil` by default.
- ///
- /// - Returns: The created `DownloadRequest`.
- open func download(_ convertible: URLConvertible,
- method: HTTPMethod = .get,
- parameters: Parameters? = nil,
- encoding: ParameterEncoding = URLEncoding.default,
- headers: HTTPHeaders? = nil,
- interceptor: RequestInterceptor? = nil,
- to destination: DownloadRequest.Destination? = nil) -> DownloadRequest {
- let convertible = RequestConvertible(url: convertible,
- method: method,
- parameters: parameters,
- encoding: encoding,
- headers: headers)
- return download(convertible, interceptor: interceptor, to: destination)
- }
- /// Creates a `DownloadRequest` from a `URLRequest` created using the passed components, `Encodable` parameters, and
- /// a `RequestInterceptor`.
- ///
- /// - Parameters:
- /// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`.
- /// - method: `HTTPMethod` for the `URLRequest`. `.get` by default.
- /// - parameters: Value conforming to `Encodable` to be encoded into the `URLRequest`. `nil` by default.
- /// - encoder: `ParameterEncoder` to be used to encode the `parameters` value into the `URLRequest`. Defaults
- /// to `URLEncodedFormParameterEncoder.default`.
- /// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default.
- /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
- /// - destination: `DownloadRequest.Destination` closure used to determine how and where the downloaded file
- /// should be moved. `nil` by default.
- ///
- /// - Returns: The created `DownloadRequest`.
- open func download<Parameters: Encodable>(_ convertible: URLConvertible,
- method: HTTPMethod = .get,
- parameters: Parameters? = nil,
- encoder: ParameterEncoder = URLEncodedFormParameterEncoder.default,
- headers: HTTPHeaders? = nil,
- interceptor: RequestInterceptor? = nil,
- to destination: DownloadRequest.Destination? = nil) -> DownloadRequest {
- let convertible = RequestEncodableConvertible(url: convertible,
- method: method,
- parameters: parameters,
- encoder: encoder,
- headers: headers)
- return download(convertible, interceptor: interceptor, to: destination)
- }
- /// Creates a `DownloadRequest` from a `URLRequestConvertible` value, a `RequestInterceptor`, and a `Destination`.
- ///
- /// - Parameters:
- /// - convertible: `URLRequestConvertible` value to be used to create the `URLRequest`.
- /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
- /// - destination: `DownloadRequest.Destination` closure used to determine how and where the downloaded file
- /// should be moved. `nil` by default.
- ///
- /// - Returns: The created `DownloadRequest`.
- open func download(_ convertible: URLRequestConvertible,
- interceptor: RequestInterceptor? = nil,
- to destination: DownloadRequest.Destination? = nil) -> DownloadRequest {
- let request = DownloadRequest(downloadable: .request(convertible),
- underlyingQueue: rootQueue,
- serializationQueue: serializationQueue,
- eventMonitor: eventMonitor,
- interceptor: interceptor,
- delegate: self,
- destination: destination ?? DownloadRequest.defaultDestination)
- perform(request)
- return request
- }
- /// Creates a `DownloadRequest` from the `resumeData` produced from a previously cancelled `DownloadRequest`, as
- /// well as a `RequestInterceptor`, and a `Destination`.
- ///
- /// - Note: If `destination` is not specified, the download will be moved to a temporary location determined by
- /// Alamofire. The file will not be deleted until the system purges the temporary files.
- ///
- /// - 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),
- /// `resumeData` is broken on background URL session configurations. There's an underlying bug in the `resumeData`
- /// generation logic where the data is written incorrectly and will always fail to resume the download. For more
- /// information about the bug and possible workarounds, please refer to the [this Stack Overflow post](http://stackoverflow.com/a/39347461/1342462).
- ///
- /// - Parameters:
- /// - data: The resume data from a previously cancelled `DownloadRequest` or `URLSessionDownloadTask`.
- /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
- /// - destination: `DownloadRequest.Destination` closure used to determine how and where the downloaded file
- /// should be moved. `nil` by default.
- ///
- /// - Returns: The created `DownloadRequest`.
- open func download(resumingWith data: Data,
- interceptor: RequestInterceptor? = nil,
- to destination: DownloadRequest.Destination? = nil) -> DownloadRequest {
- let request = DownloadRequest(downloadable: .resumeData(data),
- underlyingQueue: rootQueue,
- serializationQueue: serializationQueue,
- eventMonitor: eventMonitor,
- interceptor: interceptor,
- delegate: self,
- destination: destination ?? DownloadRequest.defaultDestination)
- perform(request)
- return request
- }
- // MARK: - UploadRequest
- struct ParameterlessRequestConvertible: URLRequestConvertible {
- let url: URLConvertible
- let method: HTTPMethod
- let headers: HTTPHeaders?
- func asURLRequest() throws -> URLRequest {
- return try URLRequest(url: url, method: method, headers: headers)
- }
- }
- struct Upload: UploadConvertible {
- let request: URLRequestConvertible
- let uploadable: UploadableConvertible
- func createUploadable() throws -> UploadRequest.Uploadable {
- return try uploadable.createUploadable()
- }
- func asURLRequest() throws -> URLRequest {
- return try request.asURLRequest()
- }
- }
- // MARK: Data
- /// Creates an `UploadRequest` for the given `Data`, `URLRequest` components, and `RequestInterceptor`.
- ///
- /// - Parameters:
- /// - data: The `Data` to upload.
- /// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`.
- /// - method: `HTTPMethod` for the `URLRequest`. `.post` by default.
- /// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default.
- /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
- /// - fileManager: `FileManager` instance to be used by the returned `UploadRequest`. `.default` instance by
- /// default.
- ///
- /// - Returns: The created `UploadRequest`.
- open func upload(_ data: Data,
- to convertible: URLConvertible,
- method: HTTPMethod = .post,
- headers: HTTPHeaders? = nil,
- interceptor: RequestInterceptor? = nil,
- fileManager: FileManager = .default) -> UploadRequest {
- let convertible = ParameterlessRequestConvertible(url: convertible, method: method, headers: headers)
- return upload(data, with: convertible, interceptor: interceptor, fileManager: fileManager)
- }
- /// Creates an `UploadRequest` for the given `Data` using the `URLRequestConvertible` value and `RequestInterceptor`.
- ///
- /// - Parameters:
- /// - data: The `Data` to upload.
- /// - convertible: `URLRequestConvertible` value to be used to create the `URLRequest`.
- /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
- /// - fileManager: `FileManager` instance to be used by the returned `UploadRequest`. `.default` instance by
- /// default.
- ///
- /// - Returns: The created `UploadRequest`.
- open func upload(_ data: Data,
- with convertible: URLRequestConvertible,
- interceptor: RequestInterceptor? = nil,
- fileManager: FileManager = .default) -> UploadRequest {
- return upload(.data(data), with: convertible, interceptor: interceptor, fileManager: fileManager)
- }
- // MARK: File
- /// Creates an `UploadRequest` for the file at the given file `URL`, using a `URLRequest` from the provided
- /// components and `RequestInterceptor`.
- ///
- /// - Parameters:
- /// - fileURL: The `URL` of the file to upload.
- /// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`.
- /// - method: `HTTPMethod` for the `URLRequest`. `.post` by default.
- /// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default.
- /// - interceptor: `RequestInterceptor` value to be used by the returned `UploadRequest`. `nil` by default.
- /// - fileManager: `FileManager` instance to be used by the returned `UploadRequest`. `.default` instance by
- /// default.
- ///
- /// - Returns: The created `UploadRequest`.
- open func upload(_ fileURL: URL,
- to convertible: URLConvertible,
- method: HTTPMethod = .post,
- headers: HTTPHeaders? = nil,
- interceptor: RequestInterceptor? = nil,
- fileManager: FileManager = .default) -> UploadRequest {
- let convertible = ParameterlessRequestConvertible(url: convertible, method: method, headers: headers)
- return upload(fileURL, with: convertible, interceptor: interceptor, fileManager: fileManager)
- }
- /// Creates an `UploadRequest` for the file at the given file `URL` using the `URLRequestConvertible` value and
- /// `RequestInterceptor`.
- ///
- /// - Parameters:
- /// - fileURL: The `URL` of the file to upload.
- /// - convertible: `URLRequestConvertible` value to be used to create the `URLRequest`.
- /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
- /// - fileManager: `FileManager` instance to be used by the returned `UploadRequest`. `.default` instance by
- /// default.
- ///
- /// - Returns: The created `UploadRequest`.
- open func upload(_ fileURL: URL,
- with convertible: URLRequestConvertible,
- interceptor: RequestInterceptor? = nil,
- fileManager: FileManager = .default) -> UploadRequest {
- return upload(.file(fileURL, shouldRemove: false), with: convertible, interceptor: interceptor, fileManager: fileManager)
- }
- // MARK: InputStream
- /// Creates an `UploadRequest` from the `InputStream` provided using a `URLRequest` from the provided components and
- /// `RequestInterceptor`.
- ///
- /// - Parameters:
- /// - stream: The `InputStream` that provides the data to upload.
- /// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`.
- /// - method: `HTTPMethod` for the `URLRequest`. `.post` by default.
- /// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default.
- /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
- /// - fileManager: `FileManager` instance to be used by the returned `UploadRequest`. `.default` instance by
- /// default.
- ///
- /// - Returns: The created `UploadRequest`.
- open func upload(_ stream: InputStream,
- to convertible: URLConvertible,
- method: HTTPMethod = .post,
- headers: HTTPHeaders? = nil,
- interceptor: RequestInterceptor? = nil,
- fileManager: FileManager = .default) -> UploadRequest {
- let convertible = ParameterlessRequestConvertible(url: convertible, method: method, headers: headers)
- return upload(stream, with: convertible, interceptor: interceptor, fileManager: fileManager)
- }
- /// Creates an `UploadRequest` from the provided `InputStream` using the `URLRequestConvertible` value and
- /// `RequestInterceptor`.
- ///
- /// - Parameters:
- /// - stream: The `InputStream` that provides the data to upload.
- /// - convertible: `URLRequestConvertible` value to be used to create the `URLRequest`.
- /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
- /// - fileManager: `FileManager` instance to be used by the returned `UploadRequest`. `.default` instance by
- /// default.
- ///
- /// - Returns: The created `UploadRequest`.
- open func upload(_ stream: InputStream,
- with convertible: URLRequestConvertible,
- interceptor: RequestInterceptor? = nil,
- fileManager: FileManager = .default) -> UploadRequest {
- return upload(.stream(stream), with: convertible, interceptor: interceptor, fileManager: fileManager)
- }
- // MARK: MultipartFormData
- /// Creates an `UploadRequest` for the multipart form data built using a closure and sent using the provided
- /// `URLRequest` components and `RequestInterceptor`.
- ///
- /// It is important to understand the memory implications of uploading `MultipartFormData`. If the cumulative
- /// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most
- /// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to
- /// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory
- /// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be
- /// used for larger payloads such as video content.
- ///
- /// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory
- /// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`,
- /// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk
- /// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding
- /// technique was used.
- ///
- /// - Parameters:
- /// - multipartFormData: `MultipartFormData` building closure.
- /// - convertible: `URLConvertible` value to be used as the `URLRequest`'s `URL`.
- /// - encodingMemoryThreshold: Byte threshold used to determine whether the form data is encoded into memory or
- /// onto disk before being uploaded. `MultipartFormData.encodingMemoryThreshold` by
- /// default.
- /// - method: `HTTPMethod` for the `URLRequest`. `.post` by default.
- /// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default.
- /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
- /// - fileManager: `FileManager` to be used if the form data exceeds the memory threshold and is
- /// written to disk before being uploaded. `.default` instance by default.
- ///
- /// - Returns: The created `UploadRequest`.
- open func upload(multipartFormData: @escaping (MultipartFormData) -> Void,
- to url: URLConvertible,
- usingThreshold encodingMemoryThreshold: UInt64 = MultipartFormData.encodingMemoryThreshold,
- method: HTTPMethod = .post,
- headers: HTTPHeaders? = nil,
- interceptor: RequestInterceptor? = nil,
- fileManager: FileManager = .default) -> UploadRequest {
- let convertible = ParameterlessRequestConvertible(url: url, method: method, headers: headers)
- let formData = MultipartFormData(fileManager: fileManager)
- multipartFormData(formData)
- return upload(multipartFormData: formData,
- with: convertible,
- usingThreshold: encodingMemoryThreshold,
- interceptor: interceptor,
- fileManager: fileManager)
- }
- /// Creates an `UploadRequest` using a `MultipartFormData` building closure, the provided `URLRequestConvertible`
- /// value, and a `RequestInterceptor`.
- ///
- /// It is important to understand the memory implications of uploading `MultipartFormData`. If the cumulative
- /// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most
- /// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to
- /// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory
- /// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be
- /// used for larger payloads such as video content.
- ///
- /// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory
- /// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`,
- /// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk
- /// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding
- /// technique was used.
- ///
- /// - Parameters:
- /// - multipartFormData: `MultipartFormData` building closure.
- /// - request: `URLRequestConvertible` value to be used to create the `URLRequest`.
- /// - encodingMemoryThreshold: Byte threshold used to determine whether the form data is encoded into memory or
- /// onto disk before being uploaded. `MultipartFormData.encodingMemoryThreshold` by
- /// default.
- /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
- /// - fileManager: `FileManager` to be used if the form data exceeds the memory threshold and is
- /// written to disk before being uploaded. `.default` instance by default.
- ///
- /// - Returns: The created `UploadRequest`.
- open func upload(multipartFormData: @escaping (MultipartFormData) -> Void,
- with request: URLRequestConvertible,
- usingThreshold encodingMemoryThreshold: UInt64 = MultipartFormData.encodingMemoryThreshold,
- interceptor: RequestInterceptor? = nil,
- fileManager: FileManager = .default) -> UploadRequest {
- let formData = MultipartFormData(fileManager: fileManager)
- multipartFormData(formData)
- return upload(multipartFormData: formData,
- with: request,
- usingThreshold: encodingMemoryThreshold,
- interceptor: interceptor,
- fileManager: fileManager)
- }
- /// Creates an `UploadRequest` for the prebuilt `MultipartFormData` value using the provided `URLRequest` components
- /// and `RequestInterceptor`.
- ///
- /// It is important to understand the memory implications of uploading `MultipartFormData`. If the cumulative
- /// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most
- /// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to
- /// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory
- /// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be
- /// used for larger payloads such as video content.
- ///
- /// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory
- /// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`,
- /// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk
- /// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding
- /// technique was used.
- ///
- /// - Parameters:
- /// - multipartFormData: `MultipartFormData` instance to upload.
- /// - url: `URLConvertible` value to be used as the `URLRequest`'s `URL`.
- /// - encodingMemoryThreshold: Byte threshold used to determine whether the form data is encoded into memory or
- /// onto disk before being uploaded. `MultipartFormData.encodingMemoryThreshold` by
- /// default.
- /// - method: `HTTPMethod` for the `URLRequest`. `.post` by default.
- /// - headers: `HTTPHeaders` value to be added to the `URLRequest`. `nil` by default.
- /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
- /// - fileManager: `FileManager` to be used if the form data exceeds the memory threshold and is
- /// written to disk before being uploaded. `.default` instance by default.
- ///
- /// - Returns: The created `UploadRequest`.
- open func upload(multipartFormData: MultipartFormData,
- to url: URLConvertible,
- usingThreshold encodingMemoryThreshold: UInt64 = MultipartFormData.encodingMemoryThreshold,
- method: HTTPMethod = .post,
- headers: HTTPHeaders? = nil,
- interceptor: RequestInterceptor? = nil,
- fileManager: FileManager = .default) -> UploadRequest {
- let convertible = ParameterlessRequestConvertible(url: url, method: method, headers: headers)
- let multipartUpload = MultipartUpload(isInBackgroundSession: session.configuration.identifier != nil,
- encodingMemoryThreshold: encodingMemoryThreshold,
- request: convertible,
- multipartFormData: multipartFormData)
- return upload(multipartUpload, interceptor: interceptor, fileManager: fileManager)
- }
- /// Creates an `UploadRequest` for the prebuilt `MultipartFormData` value using the providing `URLRequestConvertible`
- /// value and `RequestInterceptor`.
- ///
- /// It is important to understand the memory implications of uploading `MultipartFormData`. If the cumulative
- /// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most
- /// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to
- /// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory
- /// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be
- /// used for larger payloads such as video content.
- ///
- /// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory
- /// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`,
- /// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk
- /// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding
- /// technique was used.
- ///
- /// - Parameters:
- /// - multipartFormData: `MultipartFormData` instance to upload.
- /// - request: `URLRequestConvertible` value to be used to create the `URLRequest`.
- /// - encodingMemoryThreshold: Byte threshold used to determine whether the form data is encoded into memory or
- /// onto disk before being uploaded. `MultipartFormData.encodingMemoryThreshold` by
- /// default.
- /// - interceptor: `RequestInterceptor` value to be used by the returned `DataRequest`. `nil` by default.
- /// - fileManager: `FileManager` instance to be used by the returned `UploadRequest`. `.default` instance by
- /// default.
- ///
- /// - Returns: The created `UploadRequest`.
- open func upload(multipartFormData: MultipartFormData,
- with request: URLRequestConvertible,
- usingThreshold encodingMemoryThreshold: UInt64 = MultipartFormData.encodingMemoryThreshold,
- interceptor: RequestInterceptor? = nil,
- fileManager: FileManager = .default) -> UploadRequest {
- let multipartUpload = MultipartUpload(isInBackgroundSession: session.configuration.identifier != nil,
- encodingMemoryThreshold: encodingMemoryThreshold,
- request: request,
- multipartFormData: multipartFormData)
- return upload(multipartUpload, interceptor: interceptor, fileManager: fileManager)
- }
- // MARK: - Internal API
- // MARK: Uploadable
- func upload(_ uploadable: UploadRequest.Uploadable,
- with convertible: URLRequestConvertible,
- interceptor: RequestInterceptor?,
- fileManager: FileManager) -> UploadRequest {
- let uploadable = Upload(request: convertible, uploadable: uploadable)
- return upload(uploadable, interceptor: interceptor, fileManager: fileManager)
- }
- func upload(_ upload: UploadConvertible, interceptor: RequestInterceptor?, fileManager: FileManager) -> UploadRequest {
- let request = UploadRequest(convertible: upload,
- underlyingQueue: rootQueue,
- serializationQueue: serializationQueue,
- eventMonitor: eventMonitor,
- interceptor: interceptor,
- fileManager: fileManager,
- delegate: self)
- perform(request)
- return request
- }
- // MARK: Perform
- /// Perform `Request`.
- ///
- /// - Note: Called during retry.
- ///
- /// - Parameter request: The `Request` to perform.
- func perform(_ request: Request) {
- switch request {
- case let r as DataRequest: perform(r)
- case let r as UploadRequest: perform(r)
- case let r as DownloadRequest: perform(r)
- default: fatalError("Attempted to perform unsupported Request subclass: \(type(of: request))")
- }
- }
- func perform(_ request: DataRequest) {
- requestQueue.async {
- guard !request.isCancelled else { return }
- self.activeRequests.insert(request)
- self.performSetupOperations(for: request, convertible: request.convertible)
- }
- }
- func perform(_ request: UploadRequest) {
- requestQueue.async {
- guard !request.isCancelled else { return }
- self.activeRequests.insert(request)
- do {
- let uploadable = try request.upload.createUploadable()
- self.rootQueue.async { request.didCreateUploadable(uploadable) }
- self.performSetupOperations(for: request, convertible: request.convertible)
- } catch {
- self.rootQueue.async { request.didFailToCreateUploadable(with: error.asAFError(or: .createUploadableFailed(error: error))) }
- }
- }
- }
- func perform(_ request: DownloadRequest) {
- requestQueue.async {
- guard !request.isCancelled else { return }
- self.activeRequests.insert(request)
- switch request.downloadable {
- case let .request(convertible):
- self.performSetupOperations(for: request, convertible: convertible)
- case let .resumeData(resumeData):
- self.rootQueue.async { self.didReceiveResumeData(resumeData, for: request) }
- }
- }
- }
- func performSetupOperations(for request: Request, convertible: URLRequestConvertible) {
- let initialRequest: URLRequest
- do {
- initialRequest = try convertible.asURLRequest()
- try initialRequest.validate()
- } catch {
- rootQueue.async { request.didFailToCreateURLRequest(with: error.asAFError(or: .createURLRequestFailed(error: error))) }
- return
- }
- rootQueue.async { request.didCreateInitialURLRequest(initialRequest) }
- guard !request.isCancelled else { return }
- guard let adapter = adapter(for: request) else {
- rootQueue.async { self.didCreateURLRequest(initialRequest, for: request) }
- return
- }
- adapter.adapt(initialRequest, for: self) { result in
- do {
- let adaptedRequest = try result.get()
- try adaptedRequest.validate()
- self.rootQueue.async {
- request.didAdaptInitialRequest(initialRequest, to: adaptedRequest)
- self.didCreateURLRequest(adaptedRequest, for: request)
- }
- } catch {
- self.rootQueue.async { request.didFailToAdaptURLRequest(initialRequest, withError: .requestAdaptationFailed(error: error)) }
- }
- }
- }
- // MARK: - Task Handling
- func didCreateURLRequest(_ urlRequest: URLRequest, for request: Request) {
- request.didCreateURLRequest(urlRequest)
- guard !request.isCancelled else { return }
- let task = request.task(for: urlRequest, using: session)
- requestTaskMap[request] = task
- request.didCreateTask(task)
- updateStatesForTask(task, request: request)
- }
- func didReceiveResumeData(_ data: Data, for request: DownloadRequest) {
- guard !request.isCancelled else { return }
- let task = request.task(forResumeData: data, using: session)
- requestTaskMap[request] = task
- request.didCreateTask(task)
- updateStatesForTask(task, request: request)
- }
- func updateStatesForTask(_ task: URLSessionTask, request: Request) {
- request.withState { state in
- switch state {
- case .initialized, .finished:
- // Do nothing.
- break
- case .resumed:
- task.resume()
- rootQueue.async { request.didResumeTask(task) }
- case .suspended:
- task.suspend()
- rootQueue.async { request.didSuspendTask(task) }
- case .cancelled:
- // Resume to ensure metrics are gathered.
- task.resume()
- task.cancel()
- rootQueue.async { request.didCancelTask(task) }
- }
- }
- }
- // MARK: - Adapters and Retriers
- func adapter(for request: Request) -> RequestAdapter? {
- if let requestInterceptor = request.interceptor, let sessionInterceptor = interceptor {
- return Interceptor(adapters: [requestInterceptor, sessionInterceptor])
- } else {
- return request.interceptor ?? interceptor
- }
- }
- func retrier(for request: Request) -> RequestRetrier? {
- if let requestInterceptor = request.interceptor, let sessionInterceptor = interceptor {
- return Interceptor(retriers: [requestInterceptor, sessionInterceptor])
- } else {
- return request.interceptor ?? interceptor
- }
- }
- // MARK: - Invalidation
- func finishRequestsForDeinit() {
- requestTaskMap.requests.forEach { $0.finish(error: AFError.sessionDeinitialized) }
- }
- }
- // MARK: - RequestDelegate
- extension Session: RequestDelegate {
- public var sessionConfiguration: URLSessionConfiguration {
- return session.configuration
- }
- public var startImmediately: Bool { return startRequestsImmediately }
- public func cleanup(after request: Request) {
- activeRequests.remove(request)
- }
- public func retryResult(for request: Request, dueTo error: AFError, completion: @escaping (RetryResult) -> Void) {
- guard let retrier = retrier(for: request) else {
- rootQueue.async { completion(.doNotRetry) }
- return
- }
- retrier.retry(request, for: self, dueTo: error) { retryResult in
- self.rootQueue.async {
- guard let retryResultError = retryResult.error else { completion(retryResult); return }
- let retryError = AFError.requestRetryFailed(retryError: retryResultError, originalError: error)
- completion(.doNotRetryWithError(retryError))
- }
- }
- }
- public func retryRequest(_ request: Request, withDelay timeDelay: TimeInterval?) {
- rootQueue.async {
- let retry: () -> Void = {
- guard !request.isCancelled else { return }
- request.prepareForRetry()
- self.perform(request)
- }
- if let retryDelay = timeDelay {
- self.rootQueue.after(retryDelay) { retry() }
- } else {
- retry()
- }
- }
- }
- }
- // MARK: - SessionStateProvider
- extension Session: SessionStateProvider {
- func request(for task: URLSessionTask) -> Request? {
- dispatchPrecondition(condition: .onQueue(rootQueue))
- return requestTaskMap[task]
- }
- func didGatherMetricsForTask(_ task: URLSessionTask) {
- dispatchPrecondition(condition: .onQueue(rootQueue))
- let didDisassociate = requestTaskMap.disassociateIfNecessaryAfterGatheringMetricsForTask(task)
- if didDisassociate {
- waitingCompletions[task]?()
- waitingCompletions[task] = nil
- }
- }
- func didCompleteTask(_ task: URLSessionTask, completion: @escaping () -> Void) {
- dispatchPrecondition(condition: .onQueue(rootQueue))
- let didDisassociate = requestTaskMap.disassociateIfNecessaryAfterCompletingTask(task)
- if didDisassociate {
- completion()
- } else {
- waitingCompletions[task] = completion
- }
- }
- func credential(for task: URLSessionTask, in protectionSpace: URLProtectionSpace) -> URLCredential? {
- dispatchPrecondition(condition: .onQueue(rootQueue))
- return requestTaskMap[task]?.credential ??
- session.configuration.urlCredentialStorage?.defaultCredential(for: protectionSpace)
- }
- func cancelRequestsForSessionInvalidation(with error: Error?) {
- dispatchPrecondition(condition: .onQueue(rootQueue))
- requestTaskMap.requests.forEach { $0.finish(error: AFError.sessionInvalidated(error: error)) }
- }
- }
|