| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092 |
- //
- // Request.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
- /// `Request` is the common superclass of all Alamofire request types and provides common state, delegate, and callback
- /// handling.
- public class Request {
- /// State of the `Request`, with managed transitions between states set when calling `resume()`, `suspend()`, or
- /// `cancel()` on the `Request`.
- ///
- /// - initialized: Initial state of the `Request`.
- /// - resumed: Set when `resume()` is called. Any tasks created for the `Request` will have `resume()` called on
- /// them in this state.
- /// - suspended: Set when `suspend()` is called. Any tasks created for the `Request` will have `suspend()` called on
- /// them in this state.
- /// - cancelled: Set when `cancel()` is called. Any tasks created for the `Request` will have `cancel()` called on
- /// them. Unlike `resumed` or `suspended`, once in the `cancelled` state, the `Request` can no longer
- /// transition to any other state.
- public enum State {
- case initialized, resumed, suspended, cancelled
- /// Determines whether `self` can be transitioned to `state`.
- func canTransitionTo(_ state: State) -> Bool {
- switch (self, state) {
- case (.initialized, _): return true
- case (_, .initialized), (.cancelled, _): return false
- case (.resumed, .cancelled), (.suspended, .cancelled),
- (.resumed, .suspended), (.suspended, .resumed): return true
- case (.suspended, .suspended), (.resumed, .resumed): return false
- }
- }
- }
- // MARK: - Initial State
- /// `UUID` prividing a unique identifier for the `Request`, used in the `Hashable` and `Equatable` conformances.
- public let id: UUID
- /// The serial queue for all internal async actions.
- public let underlyingQueue: DispatchQueue
- /// The queue used for all serialization actions. By default it's a serial queue that targets `underlyingQueue`.
- public let serializationQueue: DispatchQueue
- /// `EventMonitor` used for event callbacks.
- public let eventMonitor: EventMonitor?
- /// The `Request`'s interceptor.
- public let interceptor: RequestInterceptor?
- /// The `Request`'s delegate.
- public private(set) weak var delegate: RequestDelegate?
- // MARK: - Updated State
- /// Type encapsulating all mutable state that may need to be accessed from anything other than the `underlyingQueue`.
- struct MutableState {
- /// State of the `Request`.
- var state: State = .initialized
- /// `ProgressHandler` and `DispatchQueue` provided for upload progress callbacks.
- var uploadProgressHandler: (handler: ProgressHandler, queue: DispatchQueue)?
- /// `ProgressHandler` and `DispatchQueue` provided for download progress callbacks.
- var downloadProgressHandler: (handler: ProgressHandler, queue: DispatchQueue)?
- /// `RetryHandler` provided for redirect responses.
- var redirectHandler: RedirectHandler?
- /// `CachedResponseHandler` provided to handle caching responses.
- var cachedResponseHandler: CachedResponseHandler?
- /// Response serialization closures that handle parsing responses.
- var responseSerializers: [() -> Void] = []
- /// Response serialization completion closures executed once all response serialization is complete.
- var responseSerializerCompletions: [() -> Void] = []
- /// `URLCredential` used for authentication challenges.
- var credential: URLCredential?
- /// All `URLRequest`s created by Alamofire on behalf of the `Request`.
- var requests: [URLRequest] = []
- /// All `URLSessionTask`s created by Alamofire on behalf of the `Request`.
- var tasks: [URLSessionTask] = []
- /// All `URLSessionTaskMetrics` values gathered by Alamofire on behalf of the `Request`. Should correspond
- /// exactly the the `tasks` created.
- var metrics: [URLSessionTaskMetrics] = []
- /// Number of times any retriers provided retried the `Request`.
- var retryCount = 0
- /// Final `Error` for the `Request`, whether from various internal Alamofire calls or as a result of a `task`.
- var error: Error?
- }
- /// Protected `MutableState` value that provides threadsafe access to state values.
- private let protectedMutableState: Protector<MutableState> = Protector(MutableState())
- /// `State` of the `Request`.
- public fileprivate(set) var state: State {
- get { return protectedMutableState.directValue.state }
- set { protectedMutableState.write { $0.state = newValue } }
- }
- /// Returns whether `state` is `.cancelled`.
- public var isCancelled: Bool { return state == .cancelled }
- /// Returns whether `state is `.resumed`.
- public var isResumed: Bool { return state == .resumed }
- /// Returns whether `state` is `.suspended`.
- public var isSuspended: Bool { return state == .suspended }
- /// Returns whether `state` is `.initialized`.
- public var isInitialized: Bool { return state == .initialized }
- // Progress
- /// Closure type executed when monitoring the upload or download progress of a request.
- public typealias ProgressHandler = (Progress) -> Void
- /// `Progress` of the upload of the body of the executed `URLRequest`. Reset to `0` if the `Request` is retried.
- public let uploadProgress = Progress(totalUnitCount: 0)
- /// `Progress` of the download of any response data. Reset to `0` if the `Request` is retried.
- public let downloadProgress = Progress(totalUnitCount: 0)
- /// `ProgressHandler` called when `uploadProgress` is updated, on the provided `DispatchQueue`.
- fileprivate var uploadProgressHandler: (handler: ProgressHandler, queue: DispatchQueue)? {
- get { return protectedMutableState.directValue.uploadProgressHandler }
- set { protectedMutableState.write { $0.uploadProgressHandler = newValue } }
- }
- /// `ProgressHandler` called when `downloadProgress` is updated, on the provided `DispatchQueue`.
- fileprivate var downloadProgressHandler: (handler: ProgressHandler, queue: DispatchQueue)? {
- get { return protectedMutableState.directValue.downloadProgressHandler }
- set { protectedMutableState.write { $0.downloadProgressHandler = newValue } }
- }
- // Redirects
- public private(set) var redirectHandler: RedirectHandler? {
- get { return protectedMutableState.directValue.redirectHandler }
- set { protectedMutableState.write { $0.redirectHandler = newValue } }
- }
- // Cached Responses
- public private(set) var cachedResponseHandler: CachedResponseHandler? {
- get { return protectedMutableState.directValue.cachedResponseHandler }
- set { protectedMutableState.write { $0.cachedResponseHandler = newValue } }
- }
- // Credential
- /// `URLCredential` used for authentication challenges. Created by calling one of the `authenticate` methods.
- public private(set) var credential: URLCredential? {
- get { return protectedMutableState.directValue.credential }
- set { protectedMutableState.write { $0.credential = newValue } }
- }
- // Validators
- /// `Validator` callback closures that store the validation calls enqueued.
- fileprivate var protectedValidators: Protector<[() -> Void]> = Protector([])
- // Requests
- /// All `URLRequests` created on behalf of the `Request`, including original and adapted requests.
- public var requests: [URLRequest] { return protectedMutableState.directValue.requests }
- /// First `URLRequest` created on behalf of the `Request`. May not be the first one actually executed.
- public var firstRequest: URLRequest? { return requests.first }
- /// Last `URLRequest` created on behalf of the `Request`.
- public var lastRequest: URLRequest? { return requests.last }
- /// Current `URLRequest` created on behalf of the `Request`.
- public var request: URLRequest? { return lastRequest }
- /// `URLRequest`s from all of the `URLSessionTask`s executed on behalf of the `Request`.
- public var performedRequests: [URLRequest] {
- return protectedMutableState.read { $0.tasks.compactMap { $0.currentRequest } }
- }
- // Response
- /// `HTTPURLResponse` received from the server, if any. If the `Request` was retried, this is the response of the
- /// last `URLSessionTask`.
- public var response: HTTPURLResponse? { return lastTask?.response as? HTTPURLResponse }
- // Tasks
- /// All `URLSessionTask`s created on behalf of the `Request`.
- public var tasks: [URLSessionTask] { return protectedMutableState.directValue.tasks }
- /// First `URLSessionTask` created on behalf of the `Request`.
- public var firstTask: URLSessionTask? { return tasks.first }
- /// Last `URLSessionTask` crated on behalf of the `Request`.
- public var lastTask: URLSessionTask? { return tasks.last }
- /// Current `URLSessionTask` created on behalf of the `Request`.
- public var task: URLSessionTask? { return lastTask }
- // Metrics
- /// All `URLSessionTaskMetrics` gathered on behalf of the `Request`. Should correspond to the `tasks` created.
- public var allMetrics: [URLSessionTaskMetrics] { return protectedMutableState.directValue.metrics }
- /// First `URLSessionTaskMetrics` gathered on behalf of the `Request`.
- public var firstMetrics: URLSessionTaskMetrics? { return allMetrics.first }
- /// Last `URLSessionTaskMetrics` gathered on behalf of the `Request`.
- public var lastMetrics: URLSessionTaskMetrics? { return allMetrics.last }
- /// Current `URLSessionTaskMetrics` gathered on behalf of the `Request`.
- public var metrics: URLSessionTaskMetrics? { return lastMetrics }
- /// Number of times the `Request` has been retried.
- public var retryCount: Int { return protectedMutableState.directValue.retryCount }
- /// `Error` returned from Alamofire internally, from the network request directly, or any validators executed.
- fileprivate(set) public var error: Error? {
- get { return protectedMutableState.directValue.error }
- set { protectedMutableState.write { $0.error = newValue } }
- }
- /// Default initializer for the `Request` superclass.
- ///
- /// - Parameters:
- /// - id: `UUID` used for the `Hashable` and `Equatable` implementations. Defaults to a random `UUID`.
- /// - underlyingQueue: `DispatchQueue` on which all internal `Request` work is performed.
- /// - serializationQueue: `DispatchQueue` on which all serialization work is performed. Targets the
- /// `underlyingQueue` when created by a `SessionManager`.
- /// - eventMonitor: `EventMonitor` used for event callbacks from internal `Request` actions.
- /// - interceptor: `RequestInterceptor` used throughout the request lifecycle.
- /// - delegate: `RequestDelegate` that provides an interface to actions not performed by the `Request`.
- public init(id: UUID = UUID(),
- underlyingQueue: DispatchQueue,
- serializationQueue: DispatchQueue,
- eventMonitor: EventMonitor?,
- interceptor: RequestInterceptor?,
- delegate: RequestDelegate) {
- self.id = id
- self.underlyingQueue = underlyingQueue
- self.serializationQueue = serializationQueue
- self.eventMonitor = eventMonitor
- self.interceptor = interceptor
- self.delegate = delegate
- }
- // MARK: - Internal API
- // Called from underlyingQueue.
- /// Called when a `URLRequest` has been created on behalf of the `Request`.
- ///
- /// - Parameter request: `URLRequest` created.
- func didCreateURLRequest(_ request: URLRequest) {
- protectedMutableState.write { $0.requests.append(request) }
- eventMonitor?.request(self, didCreateURLRequest: request)
- }
- /// Called when initial `URLRequest` creation has failed, typically through a `URLRequestConvertible`. Triggers retry.
- ///
- /// - Parameter error: `Error` thrown from the failed creation.
- func didFailToCreateURLRequest(with error: Error) {
- self.error = error
- eventMonitor?.request(self, didFailToCreateURLRequestWithError: error)
- retryOrFinish(error: error)
- }
- /// Called when a `RequestAdapter` has successfully adapted a `URLRequest`.
- ///
- /// - Parameters:
- /// - initialRequest: The `URLRequest` that was adapted.
- /// - adaptedRequest: The `URLRequest` returned by the `RequestAdapter`.
- func didAdaptInitialRequest(_ initialRequest: URLRequest, to adaptedRequest: URLRequest) {
- protectedMutableState.write { $0.requests.append(adaptedRequest) }
- eventMonitor?.request(self, didAdaptInitialRequest: initialRequest, to: adaptedRequest)
- }
- /// Called when a `RequestAdapter` fails to adapt a `URLRequest`. Triggers retry.
- ///
- /// - Parameters:
- /// - request: The `URLRequest` the adapter was called with.
- /// - error: The `Error` returned by the `RequestAdapter`.
- func didFailToAdaptURLRequest(_ request: URLRequest, withError error: Error) {
- self.error = error
- eventMonitor?.request(self, didFailToAdaptURLRequest: request, withError: error)
- retryOrFinish(error: error)
- }
- /// Called when a `URLSessionTask` is created on behalf of the `Request`.
- ///
- /// - Parameter task: The `URLSessionTask` created.
- func didCreateTask(_ task: URLSessionTask) {
- protectedMutableState.write { $0.tasks.append(task) }
- eventMonitor?.request(self, didCreateTask: task)
- }
- /// Called when resumption is completed.
- func didResume() {
- eventMonitor?.requestDidResume(self)
- }
- /// Called when a `URLSessionTask` is resumed on behalf of the instance.
- func didResumeTask(_ task: URLSessionTask) {
- eventMonitor?.request(self, didResumeTask: task)
- }
- /// Called when suspension is completed.
- func didSuspend() {
- eventMonitor?.requestDidSuspend(self)
- }
- /// Callend when a `URLSessionTask` is suspended on behalf of the instance.
- func didSuspendTask(_ task: URLSessionTask) {
- eventMonitor?.request(self, didSuspendTask: task)
- }
- /// Called when cancellation is completed, sets `error` to `AFError.explicitlyCancelled`.
- func didCancel() {
- error = AFError.explicitlyCancelled
- eventMonitor?.requestDidCancel(self)
- }
- /// Called when a `URLSessionTask` is cancelled on behalf of the instance.
- func didCancelTask(_ task: URLSessionTask) {
- eventMonitor?.request(self, didCancelTask: task)
- }
- /// Called when a `URLSessionTaskMetrics` value is gathered on behalf of the `Request`.
- func didGatherMetrics(_ metrics: URLSessionTaskMetrics) {
- protectedMutableState.write { $0.metrics.append(metrics) }
- eventMonitor?.request(self, didGatherMetrics: metrics)
- }
- /// Called when a `URLSessionTask` fails before it is finished, typically during certificate pinning.
- func didFailTask(_ task: URLSessionTask, earlyWithError error: Error) {
- self.error = error
- // Task will still complete, so didCompleteTask(_:with:) will handle retry.
- eventMonitor?.request(self, didFailTask: task, earlyWithError: error)
- }
- /// Called when a `URLSessionTask` completes. All tasks will eventually call this method.
- func didCompleteTask(_ task: URLSessionTask, with error: Error?) {
- self.error = self.error ?? error
- protectedValidators.directValue.forEach { $0() }
- eventMonitor?.request(self, didCompleteTask: task, with: error)
- retryOrFinish(error: self.error)
- }
- /// Called when the `RequestDelegate` is going to retry this `Request`. Calls `reset()`.
- func prepareForRetry() {
- protectedMutableState.write { $0.retryCount += 1 }
- reset()
- eventMonitor?.requestIsRetrying(self)
- }
- /// Called to trigger retry or finish this `Request`.
- func retryOrFinish(error: Error?) {
- guard let error = error, let delegate = delegate else { finish(); return }
- delegate.retryResult(for: self, dueTo: error) { retryResult in
- switch retryResult {
- case .doNotRetry, .doNotRetryWithError:
- self.finish(error: retryResult.error)
- case .retry, .retryWithDelay:
- delegate.retryRequest(self, withDelay: retryResult.delay)
- }
- }
- }
- /// Finishes this `Request` and starts the response serializers.
- func finish(error: Error? = nil) {
- if let error = error { self.error = error }
- // Start response handlers
- processNextResponseSerializer()
- eventMonitor?.requestDidFinish(self)
- }
- /// Appends the response serialization closure to the `Request`.
- func appendResponseSerializer(_ closure: @escaping () -> Void) {
- protectedMutableState.write { $0.responseSerializers.append(closure) }
- }
- /// Returns the next response serializer closure to execute if there's one left.
- func nextResponseSerializer() -> (() -> Void)? {
- var responseSerializer: (() -> Void)?
- protectedMutableState.write { mutableState in
- let responseSerializerIndex = mutableState.responseSerializerCompletions.count
- if responseSerializerIndex < mutableState.responseSerializers.count {
- responseSerializer = mutableState.responseSerializers[responseSerializerIndex]
- }
- }
- return responseSerializer
- }
- /// Processes the next response serializer and calls all completions if response serialization is complete.
- func processNextResponseSerializer() {
- guard let responseSerializer = nextResponseSerializer() else {
- // Execute all response serializer completions and clear them
- var completions: [() -> Void] = []
- protectedMutableState.write { mutableState in
- completions = mutableState.responseSerializerCompletions
- // Clear out all response serializers and response serializer completions in mutable state since the
- // request is complete. It's important to do this prior to calling the completion closures in case
- // the completions call back into the request triggering a re-processing of the response serializers.
- // An example of how this can happen is by calling cancel inside a response completion closure.
- mutableState.responseSerializers.removeAll()
- mutableState.responseSerializerCompletions.removeAll()
- }
- completions.forEach { $0() }
- // Cleanup the request
- cleanup()
- return
- }
- serializationQueue.async { responseSerializer() }
- }
- /// Notifies the `Request` that the response serializer is complete.
- func responseSerializerDidComplete(completion: @escaping () -> Void) {
- protectedMutableState.write { $0.responseSerializerCompletions.append(completion) }
- processNextResponseSerializer()
- }
- /// Resets all task and response serializer related state for retry.
- func reset() {
- error = nil
- uploadProgress.totalUnitCount = 0
- uploadProgress.completedUnitCount = 0
- downloadProgress.totalUnitCount = 0
- downloadProgress.completedUnitCount = 0
- protectedMutableState.write { $0.responseSerializerCompletions = [] }
- }
- /// Called when updating the upload progress.
- func updateUploadProgress(totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
- uploadProgress.totalUnitCount = totalBytesExpectedToSend
- uploadProgress.completedUnitCount = totalBytesSent
- uploadProgressHandler?.queue.async { self.uploadProgressHandler?.handler(self.uploadProgress) }
- }
- // MARK: Task Creation
- /// Called when creating a `URLSessionTask` for this `Request`. Subclasses must override.
- func task(for request: URLRequest, using session: URLSession) -> URLSessionTask {
- fatalError("Subclasses must override.")
- }
- // MARK: - Public API
- // These APIs are callable from any queue.
- // MARK: - State
- /// Cancels the `Request`. Once cancelled, a `Request` can no longer be resumed or suspended.
- ///
- /// - Returns: The `Request`.
- @discardableResult
- public func cancel() -> Self {
- guard protectedMutableState.attemptToTransitionTo(.cancelled) else { return self }
- delegate?.cancelRequest(self)
- return self
- }
- /// Suspends the `Request`.
- ///
- /// - Returns: The `Request`.
- @discardableResult
- public func suspend() -> Self {
- guard protectedMutableState.attemptToTransitionTo(.suspended) else { return self }
- delegate?.suspendRequest(self)
- return self
- }
- /// Resumes the `Request`.
- ///
- /// - Returns: The `Request`.
- @discardableResult
- public func resume() -> Self {
- guard protectedMutableState.attemptToTransitionTo(.resumed) else { return self }
- delegate?.resumeRequest(self)
- return self
- }
- // MARK: - Closure API
- /// Associates a credential using the provided values with the `Request`.
- ///
- /// - Parameters:
- /// - username: The username.
- /// - password: The password.
- /// - persistence: The `URLCredential.Persistence` for the created `URLCredential`.
- /// - Returns: The `Request`.
- @discardableResult
- public func authenticate(username: String, password: String, persistence: URLCredential.Persistence = .forSession) -> Self {
- let credential = URLCredential(user: username, password: password, persistence: persistence)
- return authenticate(with: credential)
- }
- /// Associates the provided credential with the `Request`.
- ///
- /// - Parameter credential: The `URLCredential`.
- /// - Returns: The `Request`.
- @discardableResult
- public func authenticate(with credential: URLCredential) -> Self {
- protectedMutableState.write { $0.credential = credential }
- return self
- }
- /// Sets a closure to be called periodically during the lifecycle of the `Request` as data is read from the server.
- ///
- /// Only the last closure provided is used.
- ///
- /// - Parameters:
- /// - queue: The `DispatchQueue` to execute the closure on. Defaults to `.main`.
- /// - closure: The code to be executed periodically as data is read from the server.
- /// - Returns: The `Request`.
- @discardableResult
- public func downloadProgress(queue: DispatchQueue = .main, closure: @escaping ProgressHandler) -> Self {
- protectedMutableState.write { $0.downloadProgressHandler = (handler: closure, queue: queue) }
- return self
- }
- /// Sets a closure to be called periodically during the lifecycle of the `Request` as data is sent to the server.
- ///
- /// Only the last closure provided is used.
- ///
- /// - Parameters:
- /// - queue: The `DispatchQueue` to execute the closure on. Defaults to `.main`.
- /// - closure: The closure to be executed periodically as data is sent to the server.
- /// - Returns: The `Request`.
- @discardableResult
- public func uploadProgress(queue: DispatchQueue = .main, closure: @escaping ProgressHandler) -> Self {
- protectedMutableState.write { $0.uploadProgressHandler = (handler: closure, queue: queue) }
- return self
- }
- // MARK: - Redirects
- /// Sets the redirect handler for the `Request` which will be used if a redirect response is encountered.
- ///
- /// - Parameter handler: The `RedirectHandler`.
- /// - Returns: The `Request`.
- @discardableResult
- public func redirect(using handler: RedirectHandler) -> Self {
- protectedMutableState.write { mutableState in
- precondition(mutableState.redirectHandler == nil, "Redirect handler has already been set")
- mutableState.redirectHandler = handler
- }
- return self
- }
- // MARK: - Cached Responses
- /// Sets the cached response handler for the `Request` which will be used when attempting to cache a response.
- ///
- /// - Parameter handler: The `CachedResponseHandler`.
- /// - Returns: The `Request`.
- @discardableResult
- public func cacheResponse(using handler: CachedResponseHandler) -> Self {
- protectedMutableState.write { mutableState in
- precondition(mutableState.cachedResponseHandler == nil, "Cached response handler has already been set")
- mutableState.cachedResponseHandler = handler
- }
- return self
- }
- // MARK: - Cleanup
- /// Final cleanup step executed when a `Request` finishes response serialization.
- open func cleanup() {
- // No-op: override in subclass
- }
- }
- // MARK: - Protocol Conformances
- extension Request: Equatable {
- public static func == (lhs: Request, rhs: Request) -> Bool {
- return lhs.id == rhs.id
- }
- }
- extension Request: Hashable {
- public func hash(into hasher: inout Hasher) {
- hasher.combine(id)
- }
- }
- extension Request: CustomStringConvertible {
- /// A textual representation of this instance, including the `HTTPMethod` and `URL` if the `URLRequest` has been
- /// created, as well as the response status code, if a response has been received.
- public var description: String {
- guard let request = performedRequests.last ?? lastRequest,
- let url = request.url,
- let method = request.httpMethod else { return "No request created yet." }
- let requestDescription = "\(method) \(url.absoluteString)"
- return response.map { "\(requestDescription) (\($0.statusCode))" } ?? requestDescription
- }
- }
- extension Request: CustomDebugStringConvertible {
- /// A textual representation of this instance in the form of a cURL command.
- public var debugDescription: String {
- return cURLRepresentation()
- }
- func cURLRepresentation() -> String {
- guard
- let request = lastRequest,
- let url = request.url,
- let host = url.host,
- let method = request.httpMethod else { return "$ curl command could not be created" }
- var components = ["$ curl -v"]
- components.append("-X \(method)")
- if let credentialStorage = delegate?.sessionConfiguration.urlCredentialStorage {
- let protectionSpace = URLProtectionSpace(
- host: host,
- port: url.port ?? 0,
- protocol: url.scheme,
- realm: host,
- authenticationMethod: NSURLAuthenticationMethodHTTPBasic
- )
- if let credentials = credentialStorage.credentials(for: protectionSpace)?.values {
- for credential in credentials {
- guard let user = credential.user, let password = credential.password else { continue }
- components.append("-u \(user):\(password)")
- }
- } else {
- if let credential = credential, let user = credential.user, let password = credential.password {
- components.append("-u \(user):\(password)")
- }
- }
- }
- if let configuration = delegate?.sessionConfiguration, configuration.httpShouldSetCookies {
- if
- let cookieStorage = configuration.httpCookieStorage,
- let cookies = cookieStorage.cookies(for: url), !cookies.isEmpty
- {
- let allCookies = cookies.map { "\($0.name)=\($0.value)" }.joined(separator: ";")
- components.append("-b \"\(allCookies)\"")
- }
- }
- var headers: [String: String] = [:]
- if let additionalHeaders = delegate?.sessionConfiguration.httpAdditionalHeaders as? [String: String] {
- for (field, value) in additionalHeaders where field != "Cookie" {
- headers[field] = value
- }
- }
- if let headerFields = request.allHTTPHeaderFields {
- for (field, value) in headerFields where field != "Cookie" {
- headers[field] = value
- }
- }
- for (field, value) in headers {
- let escapedValue = value.replacingOccurrences(of: "\"", with: "\\\"")
- components.append("-H \"\(field): \(escapedValue)\"")
- }
- if let httpBodyData = request.httpBody, let httpBody = String(data: httpBodyData, encoding: .utf8) {
- var escapedBody = httpBody.replacingOccurrences(of: "\\\"", with: "\\\\\"")
- escapedBody = escapedBody.replacingOccurrences(of: "\"", with: "\\\"")
- components.append("-d \"\(escapedBody)\"")
- }
- components.append("\"\(url.absoluteString)\"")
- return components.joined(separator: " \\\n\t")
- }
- }
- /// Protocol abstraction for `Request`'s communication back to the `SessionDelegate`.
- public protocol RequestDelegate: AnyObject {
- var sessionConfiguration: URLSessionConfiguration { get }
- func retryResult(for request: Request, dueTo error: Error, completion: @escaping (RetryResult) -> Void)
- func retryRequest(_ request: Request, withDelay timeDelay: TimeInterval?)
- func cancelRequest(_ request: Request)
- func cancelDownloadRequest(_ request: DownloadRequest, byProducingResumeData: @escaping (Data?) -> Void)
- func suspendRequest(_ request: Request)
- func resumeRequest(_ request: Request)
- }
- // MARK: - Subclasses
- // MARK: DataRequest
- public class DataRequest: Request {
- public let convertible: URLRequestConvertible
- private var protectedData: Protector<Data?> = Protector(nil)
- public var data: Data? { return protectedData.directValue }
- init(id: UUID = UUID(),
- convertible: URLRequestConvertible,
- underlyingQueue: DispatchQueue,
- serializationQueue: DispatchQueue,
- eventMonitor: EventMonitor?,
- interceptor: RequestInterceptor?,
- delegate: RequestDelegate) {
- self.convertible = convertible
- super.init(id: id,
- underlyingQueue: underlyingQueue,
- serializationQueue: serializationQueue,
- eventMonitor: eventMonitor,
- interceptor: interceptor,
- delegate: delegate)
- }
- override func reset() {
- super.reset()
- protectedData.directValue = nil
- }
- func didReceive(data: Data) {
- if self.data == nil {
- protectedData.directValue = data
- } else {
- protectedData.append(data)
- }
- updateDownloadProgress()
- }
- override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask {
- let copiedRequest = request
- return session.dataTask(with: copiedRequest)
- }
- func updateDownloadProgress() {
- let totalBytesRecieved = Int64(data?.count ?? 0)
- let totalBytesExpected = task?.response?.expectedContentLength ?? NSURLSessionTransferSizeUnknown
- downloadProgress.totalUnitCount = totalBytesExpected
- downloadProgress.completedUnitCount = totalBytesRecieved
- downloadProgressHandler?.queue.async { self.downloadProgressHandler?.handler(self.downloadProgress) }
- }
- /// Validates the request, using the specified closure.
- ///
- /// If validation fails, subsequent calls to response handlers will have an associated error.
- ///
- /// - parameter validation: A closure to validate the request.
- ///
- /// - returns: The request.
- @discardableResult
- public func validate(_ validation: @escaping Validation) -> Self {
- let validator: () -> Void = { [unowned self] in
- guard self.error == nil, let response = self.response else { return }
- let result = validation(self.request, response, self.data)
- if case .failure(let error) = result { self.error = error }
- self.eventMonitor?.request(self,
- didValidateRequest: self.request,
- response: response,
- data: self.data,
- withResult: result)
- }
- protectedValidators.append(validator)
- return self
- }
- }
- public class DownloadRequest: Request {
- /// A collection of options to be executed prior to moving a downloaded file from the temporary URL to the
- /// destination URL.
- public struct Options: OptionSet {
- /// A `DownloadOptions` flag that creates intermediate directories for the destination URL if specified.
- public static let createIntermediateDirectories = Options(rawValue: 1 << 0)
- /// A `DownloadOptions` flag that removes a previous file from the destination URL if specified.
- public static let removePreviousFile = Options(rawValue: 1 << 1)
- /// Returns the raw bitmask value of the option and satisfies the `RawRepresentable` protocol.
- public let rawValue: Int
- /// Creates a `DownloadRequest.Options` instance with the specified raw value.
- ///
- /// - parameter rawValue: The raw bitmask value for the option.
- ///
- /// - returns: A new `DownloadRequest.Options` instance.
- public init(rawValue: Int) {
- self.rawValue = rawValue
- }
- }
- /// A closure executed once a download request has successfully completed in order to determine where to move the
- /// temporary file written to during the download process. The closure takes two arguments: the temporary file URL
- /// and the URL response, and returns a two arguments: the file URL where the temporary file should be moved and
- /// the options defining how the file should be moved.
- public typealias Destination = (_ temporaryURL: URL,
- _ response: HTTPURLResponse) -> (destinationURL: URL, options: Options)
- // MARK: Destination
- /// Creates a download file destination closure which uses the default file manager to move the temporary file to a
- /// file URL in the first available directory with the specified search path directory and search path domain mask.
- ///
- /// - parameter directory: The search path directory. `.documentDirectory` by default.
- /// - parameter domain: The search path domain mask. `.userDomainMask` by default.
- ///
- /// - returns: A download file destination closure.
- public class func suggestedDownloadDestination(for directory: FileManager.SearchPathDirectory = .documentDirectory,
- in domain: FileManager.SearchPathDomainMask = .userDomainMask,
- options: Options = []) -> Destination {
- return { temporaryURL, response in
- let directoryURLs = FileManager.default.urls(for: directory, in: domain)
- let url = directoryURLs.first?.appendingPathComponent(response.suggestedFilename!) ?? temporaryURL
- return (url, options)
- }
- }
- static let defaultDestination: Destination = { (url, _) in
- let filename = "Alamofire_\(url.lastPathComponent)"
- let destination = url.deletingLastPathComponent().appendingPathComponent(filename)
- return (destination, [])
- }
- public enum Downloadable {
- case request(URLRequestConvertible)
- case resumeData(Data)
- }
- // MARK: Initial State
- public let downloadable: Downloadable
- let destination: Destination?
- // MARK: Updated State
- private struct DownloadRequestMutableState {
- var resumeData: Data?
- var fileURL: URL?
- }
- private let protectedMutableState: Protector<DownloadRequestMutableState> = Protector(DownloadRequestMutableState())
- public var resumeData: Data? { return protectedMutableState.directValue.resumeData }
- public var fileURL: URL? { return protectedMutableState.directValue.fileURL }
- // MARK: Init
- init(id: UUID = UUID(),
- downloadable: Downloadable,
- underlyingQueue: DispatchQueue,
- serializationQueue: DispatchQueue,
- eventMonitor: EventMonitor?,
- interceptor: RequestInterceptor?,
- delegate: RequestDelegate,
- destination: Destination? = nil) {
- self.downloadable = downloadable
- self.destination = destination
- super.init(id: id,
- underlyingQueue: underlyingQueue,
- serializationQueue: serializationQueue,
- eventMonitor: eventMonitor,
- interceptor: interceptor,
- delegate: delegate)
- }
- override func reset() {
- super.reset()
- protectedMutableState.write { $0.resumeData = nil }
- protectedMutableState.write { $0.fileURL = nil }
- }
- func didFinishDownloading(using task: URLSessionTask, with result: AFResult<URL>) {
- eventMonitor?.request(self, didFinishDownloadingUsing: task, with: result)
- switch result {
- case .success(let url): protectedMutableState.write { $0.fileURL = url }
- case .failure(let error): self.error = error
- }
- }
- func updateDownloadProgress(bytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
- downloadProgress.totalUnitCount = totalBytesExpectedToWrite
- downloadProgress.completedUnitCount += bytesWritten
- downloadProgressHandler?.queue.async { self.downloadProgressHandler?.handler(self.downloadProgress) }
- }
- override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask {
- return session.downloadTask(with: request)
- }
- public func task(forResumeData data: Data, using session: URLSession) -> URLSessionTask {
- return session.downloadTask(withResumeData: data)
- }
- @discardableResult
- public override func cancel() -> Self {
- guard state.canTransitionTo(.cancelled) else { return self }
- state = .cancelled
- delegate?.cancelDownloadRequest(self) { (resumeData) in
- self.protectedMutableState.write { $0.resumeData = resumeData }
- }
- eventMonitor?.requestDidCancel(self)
- return self
- }
- /// Validates the request, using the specified closure.
- ///
- /// If validation fails, subsequent calls to response handlers will have an associated error.
- ///
- /// - parameter validation: A closure to validate the request.
- ///
- /// - returns: The request.
- @discardableResult
- public func validate(_ validation: @escaping Validation) -> Self {
- let validator: () -> Void = { [unowned self] in
- guard self.error == nil, let response = self.response else { return }
- let result = validation(self.request, response, self.fileURL)
- if case .failure(let error) = result { self.error = error }
- self.eventMonitor?.request(self,
- didValidateRequest: self.request,
- response: response,
- fileURL: self.fileURL,
- withResult: result)
- }
- protectedValidators.append(validator)
- return self
- }
- }
- public class UploadRequest: DataRequest {
- public enum Uploadable {
- case data(Data)
- case file(URL, shouldRemove: Bool)
- case stream(InputStream)
- }
- // MARK: - Initial State
- public let upload: UploadableConvertible
- // MARK: - Updated State
- public var uploadable: Uploadable?
- init(id: UUID = UUID(),
- convertible: UploadConvertible,
- underlyingQueue: DispatchQueue,
- serializationQueue: DispatchQueue,
- eventMonitor: EventMonitor?,
- interceptor: RequestInterceptor?,
- delegate: RequestDelegate) {
- self.upload = convertible
- super.init(id: id,
- convertible: convertible,
- underlyingQueue: underlyingQueue,
- serializationQueue: serializationQueue,
- eventMonitor: eventMonitor,
- interceptor: interceptor,
- delegate: delegate)
- }
- func didCreateUploadable(_ uploadable: Uploadable) {
- self.uploadable = uploadable
- eventMonitor?.request(self, didCreateUploadable: uploadable)
- }
- func didFailToCreateUploadable(with error: Error) {
- self.error = error
- eventMonitor?.request(self, didFailToCreateUploadableWithError: error)
- retryOrFinish(error: error)
- }
- override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask {
- guard let uploadable = uploadable else {
- fatalError("Attempting to create a URLSessionUploadTask when Uploadable value doesn't exist.")
- }
- switch uploadable {
- case let .data(data): return session.uploadTask(with: request, from: data)
- case let .file(url, _): return session.uploadTask(with: request, fromFile: url)
- case .stream: return session.uploadTask(withStreamedRequest: request)
- }
- }
- func inputStream() -> InputStream {
- guard let uploadable = uploadable else {
- fatalError("Attempting to access the input stream but the uploadable doesn't exist.")
- }
- guard case let .stream(stream) = uploadable else {
- fatalError("Attempted to access the stream of an UploadRequest that wasn't created with one.")
- }
- eventMonitor?.request(self, didProvideInputStream: stream)
- return stream
- }
- public override func cleanup() {
- super.cleanup()
- guard
- let uploadable = self.uploadable,
- case let .file(url, shouldRemove) = uploadable,
- shouldRemove
- else { return }
- // TODO: Abstract file manager
- try? FileManager.default.removeItem(at: url)
- }
- }
- public protocol UploadableConvertible {
- func createUploadable() throws -> UploadRequest.Uploadable
- }
- extension UploadRequest.Uploadable: UploadableConvertible {
- public func createUploadable() throws -> UploadRequest.Uploadable {
- return self
- }
- }
- public protocol UploadConvertible: UploadableConvertible & URLRequestConvertible { }
|