4 // Copyright (c) 2014-2017 Alamofire Software Foundation (http://alamofire.org/)
6 // Permission is hereby granted, free of charge, to any person obtaining a copy
7 // of this software and associated documentation files (the "Software"), to deal
8 // in the Software without restriction, including without limitation the rights
9 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 // copies of the Software, and to permit persons to whom the Software is
11 // furnished to do so, subject to the following conditions:
13 // The above copyright notice and this permission notice shall be included in
14 // all copies or substantial portions of the Software.
16 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
27 /// A type that can inspect and optionally adapt a `URLRequest` in some manner if necessary.
28 public protocol RequestAdapter {
29 /// Inspects and adapts the specified `URLRequest` in some manner if necessary and returns the result.
31 /// - parameter urlRequest: The URL request to adapt.
33 /// - throws: An `Error` if the adaptation encounters an error.
35 /// - returns: The adapted `URLRequest`.
36 func adapt(_ urlRequest: URLRequest) throws -> URLRequest
41 /// A closure executed when the `RequestRetrier` determines whether a `Request` should be retried or not.
42 public typealias RequestRetryCompletion = (_ shouldRetry: Bool, _ timeDelay: TimeInterval) -> Void
44 /// A type that determines whether a request should be retried after being executed by the specified session manager
45 /// and encountering an error.
46 public protocol RequestRetrier {
47 /// Determines whether the `Request` should be retried by calling the `completion` closure.
49 /// This operation is fully asynchronous. Any amount of time can be taken to determine whether the request needs
50 /// to be retried. The one requirement is that the completion closure is called to ensure the request is properly
53 /// - parameter manager: The session manager the request was executed on.
54 /// - parameter request: The request that failed due to the encountered error.
55 /// - parameter error: The error encountered when executing the request.
56 /// - parameter completion: The completion closure to be executed when retry decision has been determined.
57 func should(_ manager: SessionManager, retry request: Request, with error: Error, completion: @escaping RequestRetryCompletion)
62 protocol TaskConvertible {
63 func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask
66 /// A dictionary of headers to apply to a `URLRequest`.
67 public typealias HTTPHeaders = [String: String]
71 /// Responsible for sending a request and receiving the response and associated data from the server, as well as
72 /// managing its underlying `URLSessionTask`.
77 /// A closure executed when monitoring upload or download progress of a request.
78 public typealias ProgressHandler = (Progress) -> Void
81 case data(TaskConvertible?, URLSessionTask?)
82 case download(TaskConvertible?, URLSessionTask?)
83 case upload(TaskConvertible?, URLSessionTask?)
84 case stream(TaskConvertible?, URLSessionTask?)
89 /// The delegate for the underlying task.
90 open internal(set) var delegate: TaskDelegate {
92 taskDelegateLock.lock() ; defer { taskDelegateLock.unlock() }
96 taskDelegateLock.lock() ; defer { taskDelegateLock.unlock() }
97 taskDelegate = newValue
101 /// The underlying task.
102 open var task: URLSessionTask? { return delegate.task }
104 /// The session belonging to the underlying task.
105 open let session: URLSession
107 /// The request sent or to be sent to the server.
108 open var request: URLRequest? { return task?.originalRequest }
110 /// The response received from the server, if any.
111 open var response: HTTPURLResponse? { return task?.response as? HTTPURLResponse }
113 /// The number of times the request has been retried.
114 open internal(set) var retryCount: UInt = 0
116 let originalTask: TaskConvertible?
118 var startTime: CFAbsoluteTime?
119 var endTime: CFAbsoluteTime?
121 var validations: [() -> Void] = []
123 private var taskDelegate: TaskDelegate
124 private var taskDelegateLock = NSLock()
128 init(session: URLSession, requestTask: RequestTask, error: Error? = nil) {
129 self.session = session
132 case .data(let originalTask, let task):
133 taskDelegate = DataTaskDelegate(task: task)
134 self.originalTask = originalTask
135 case .download(let originalTask, let task):
136 taskDelegate = DownloadTaskDelegate(task: task)
137 self.originalTask = originalTask
138 case .upload(let originalTask, let task):
139 taskDelegate = UploadTaskDelegate(task: task)
140 self.originalTask = originalTask
141 case .stream(let originalTask, let task):
142 taskDelegate = TaskDelegate(task: task)
143 self.originalTask = originalTask
146 delegate.error = error
147 delegate.queue.addOperation { self.endTime = CFAbsoluteTimeGetCurrent() }
150 // MARK: Authentication
152 /// Associates an HTTP Basic credential with the request.
154 /// - parameter user: The user.
155 /// - parameter password: The password.
156 /// - parameter persistence: The URL credential persistence. `.ForSession` by default.
158 /// - returns: The request.
160 open func authenticate(
163 persistence: URLCredential.Persistence = .forSession)
166 let credential = URLCredential(user: user, password: password, persistence: persistence)
167 return authenticate(usingCredential: credential)
170 /// Associates a specified credential with the request.
172 /// - parameter credential: The credential.
174 /// - returns: The request.
176 open func authenticate(usingCredential credential: URLCredential) -> Self {
177 delegate.credential = credential
181 /// Returns a base64 encoded basic authentication credential as an authorization header tuple.
183 /// - parameter user: The user.
184 /// - parameter password: The password.
186 /// - returns: A tuple with Authorization header and credential value if encoding succeeds, `nil` otherwise.
187 open static func authorizationHeader(user: String, password: String) -> (key: String, value: String)? {
188 guard let data = "\(user):\(password)".data(using: .utf8) else { return nil }
190 let credential = data.base64EncodedString(options: [])
192 return (key: "Authorization", value: "Basic \(credential)")
197 /// Resumes the request.
199 guard let task = task else { delegate.queue.isSuspended = false ; return }
201 if startTime == nil { startTime = CFAbsoluteTimeGetCurrent() }
205 NotificationCenter.default.post(
206 name: Notification.Name.Task.DidResume,
208 userInfo: [Notification.Key.Task: task]
212 /// Suspends the request.
213 open func suspend() {
214 guard let task = task else { return }
218 NotificationCenter.default.post(
219 name: Notification.Name.Task.DidSuspend,
221 userInfo: [Notification.Key.Task: task]
225 /// Cancels the request.
227 guard let task = task else { return }
231 NotificationCenter.default.post(
232 name: Notification.Name.Task.DidCancel,
234 userInfo: [Notification.Key.Task: task]
239 // MARK: - CustomStringConvertible
241 extension Request: CustomStringConvertible {
242 /// The textual representation used when written to an output stream, which includes the HTTP method and URL, as
243 /// well as the response status code if a response has been received.
244 open var description: String {
245 var components: [String] = []
247 if let HTTPMethod = request?.httpMethod {
248 components.append(HTTPMethod)
251 if let urlString = request?.url?.absoluteString {
252 components.append(urlString)
255 if let response = response {
256 components.append("(\(response.statusCode))")
259 return components.joined(separator: " ")
263 // MARK: - CustomDebugStringConvertible
265 extension Request: CustomDebugStringConvertible {
266 /// The textual representation used when written to an output stream, in the form of a cURL command.
267 open var debugDescription: String {
268 return cURLRepresentation()
271 func cURLRepresentation() -> String {
272 var components = ["$ curl -v"]
274 guard let request = self.request,
275 let url = request.url,
278 return "$ curl command could not be created"
281 if let httpMethod = request.httpMethod, httpMethod != "GET" {
282 components.append("-X \(httpMethod)")
285 if let credentialStorage = self.session.configuration.urlCredentialStorage {
286 let protectionSpace = URLProtectionSpace(
289 protocol: url.scheme,
291 authenticationMethod: NSURLAuthenticationMethodHTTPBasic
294 if let credentials = credentialStorage.credentials(for: protectionSpace)?.values {
295 for credential in credentials {
296 guard let user = credential.user, let password = credential.password else { continue }
297 components.append("-u \(user):\(password)")
300 if let credential = delegate.credential, let user = credential.user, let password = credential.password {
301 components.append("-u \(user):\(password)")
306 if session.configuration.httpShouldSetCookies {
308 let cookieStorage = session.configuration.httpCookieStorage,
309 let cookies = cookieStorage.cookies(for: url), !cookies.isEmpty
311 let string = cookies.reduce("") { $0 + "\($1.name)=\($1.value);" }
314 components.append("-b \"\(string[..<string.index(before: string.endIndex)])\"")
316 components.append("-b \"\(string.substring(to: string.characters.index(before: string.endIndex)))\"")
321 var headers: [AnyHashable: Any] = [:]
323 if let additionalHeaders = session.configuration.httpAdditionalHeaders {
324 for (field, value) in additionalHeaders where field != AnyHashable("Cookie") {
325 headers[field] = value
329 if let headerFields = request.allHTTPHeaderFields {
330 for (field, value) in headerFields where field != "Cookie" {
331 headers[field] = value
335 for (field, value) in headers {
336 components.append("-H \"\(field): \(value)\"")
339 if let httpBodyData = request.httpBody, let httpBody = String(data: httpBodyData, encoding: .utf8) {
340 var escapedBody = httpBody.replacingOccurrences(of: "\\\"", with: "\\\\\"")
341 escapedBody = escapedBody.replacingOccurrences(of: "\"", with: "\\\"")
343 components.append("-d \"\(escapedBody)\"")
346 components.append("\"\(url.absoluteString)\"")
348 return components.joined(separator: " \\\n\t")
354 /// Specific type of `Request` that manages an underlying `URLSessionDataTask`.
355 open class DataRequest: Request {
357 // MARK: Helper Types
359 struct Requestable: TaskConvertible {
360 let urlRequest: URLRequest
362 func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask {
364 let urlRequest = try self.urlRequest.adapt(using: adapter)
365 return queue.sync { session.dataTask(with: urlRequest) }
367 throw AdaptError(error: error)
374 /// The request sent or to be sent to the server.
375 open override var request: URLRequest? {
376 if let request = super.request { return request }
377 if let requestable = originalTask as? Requestable { return requestable.urlRequest }
382 /// The progress of fetching the response data from the server for the request.
383 open var progress: Progress { return dataDelegate.progress }
385 var dataDelegate: DataTaskDelegate { return delegate as! DataTaskDelegate }
389 /// Sets a closure to be called periodically during the lifecycle of the request as data is read from the server.
391 /// This closure returns the bytes most recently received from the server, not including data from previous calls.
392 /// If this closure is set, data will only be available within this closure, and will not be saved elsewhere. It is
393 /// also important to note that the server data in any `Response` object will be `nil`.
395 /// - parameter closure: The code to be executed periodically during the lifecycle of the request.
397 /// - returns: The request.
399 open func stream(closure: ((Data) -> Void)? = nil) -> Self {
400 dataDelegate.dataStream = closure
406 /// Sets a closure to be called periodically during the lifecycle of the `Request` as data is read from the server.
408 /// - parameter queue: The dispatch queue to execute the closure on.
409 /// - parameter closure: The code to be executed periodically as data is read from the server.
411 /// - returns: The request.
413 open func downloadProgress(queue: DispatchQueue = DispatchQueue.main, closure: @escaping ProgressHandler) -> Self {
414 dataDelegate.progressHandler = (closure, queue)
421 /// Specific type of `Request` that manages an underlying `URLSessionDownloadTask`.
422 open class DownloadRequest: Request {
424 // MARK: Helper Types
426 /// A collection of options to be executed prior to moving a downloaded file from the temporary URL to the
428 public struct DownloadOptions: OptionSet {
429 /// Returns the raw bitmask value of the option and satisfies the `RawRepresentable` protocol.
430 public let rawValue: UInt
432 /// A `DownloadOptions` flag that creates intermediate directories for the destination URL if specified.
433 public static let createIntermediateDirectories = DownloadOptions(rawValue: 1 << 0)
435 /// A `DownloadOptions` flag that removes a previous file from the destination URL if specified.
436 public static let removePreviousFile = DownloadOptions(rawValue: 1 << 1)
438 /// Creates a `DownloadFileDestinationOptions` instance with the specified raw value.
440 /// - parameter rawValue: The raw bitmask value for the option.
442 /// - returns: A new log level instance.
443 public init(rawValue: UInt) {
444 self.rawValue = rawValue
448 /// A closure executed once a download request has successfully completed in order to determine where to move the
449 /// temporary file written to during the download process. The closure takes two arguments: the temporary file URL
450 /// and the URL response, and returns a two arguments: the file URL where the temporary file should be moved and
451 /// the options defining how the file should be moved.
452 public typealias DownloadFileDestination = (
454 _ response: HTTPURLResponse)
455 -> (destinationURL: URL, options: DownloadOptions)
457 enum Downloadable: TaskConvertible {
458 case request(URLRequest)
459 case resumeData(Data)
461 func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask {
463 let task: URLSessionTask
466 case let .request(urlRequest):
467 let urlRequest = try urlRequest.adapt(using: adapter)
468 task = queue.sync { session.downloadTask(with: urlRequest) }
469 case let .resumeData(resumeData):
470 task = queue.sync { session.downloadTask(withResumeData: resumeData) }
475 throw AdaptError(error: error)
482 /// The request sent or to be sent to the server.
483 open override var request: URLRequest? {
484 if let request = super.request { return request }
486 if let downloadable = originalTask as? Downloadable, case let .request(urlRequest) = downloadable {
493 /// The resume data of the underlying download task if available after a failure.
494 open var resumeData: Data? { return downloadDelegate.resumeData }
496 /// The progress of downloading the response data from the server for the request.
497 open var progress: Progress { return downloadDelegate.progress }
499 var downloadDelegate: DownloadTaskDelegate { return delegate as! DownloadTaskDelegate }
503 /// Cancels the request.
504 open override func cancel() {
505 downloadDelegate.downloadTask.cancel { self.downloadDelegate.resumeData = $0 }
507 NotificationCenter.default.post(
508 name: Notification.Name.Task.DidCancel,
510 userInfo: [Notification.Key.Task: task as Any]
516 /// Sets a closure to be called periodically during the lifecycle of the `Request` as data is read from the server.
518 /// - parameter queue: The dispatch queue to execute the closure on.
519 /// - parameter closure: The code to be executed periodically as data is read from the server.
521 /// - returns: The request.
523 open func downloadProgress(queue: DispatchQueue = DispatchQueue.main, closure: @escaping ProgressHandler) -> Self {
524 downloadDelegate.progressHandler = (closure, queue)
530 /// Creates a download file destination closure which uses the default file manager to move the temporary file to a
531 /// file URL in the first available directory with the specified search path directory and search path domain mask.
533 /// - parameter directory: The search path directory. `.DocumentDirectory` by default.
534 /// - parameter domain: The search path domain mask. `.UserDomainMask` by default.
536 /// - returns: A download file destination closure.
537 open class func suggestedDownloadDestination(
538 for directory: FileManager.SearchPathDirectory = .documentDirectory,
539 in domain: FileManager.SearchPathDomainMask = .userDomainMask)
540 -> DownloadFileDestination
542 return { temporaryURL, response in
543 let directoryURLs = FileManager.default.urls(for: directory, in: domain)
545 if !directoryURLs.isEmpty {
546 return (directoryURLs[0].appendingPathComponent(response.suggestedFilename!), [])
549 return (temporaryURL, [])
556 /// Specific type of `Request` that manages an underlying `URLSessionUploadTask`.
557 open class UploadRequest: DataRequest {
559 // MARK: Helper Types
561 enum Uploadable: TaskConvertible {
562 case data(Data, URLRequest)
563 case file(URL, URLRequest)
564 case stream(InputStream, URLRequest)
566 func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask {
568 let task: URLSessionTask
571 case let .data(data, urlRequest):
572 let urlRequest = try urlRequest.adapt(using: adapter)
573 task = queue.sync { session.uploadTask(with: urlRequest, from: data) }
574 case let .file(url, urlRequest):
575 let urlRequest = try urlRequest.adapt(using: adapter)
576 task = queue.sync { session.uploadTask(with: urlRequest, fromFile: url) }
577 case let .stream(_, urlRequest):
578 let urlRequest = try urlRequest.adapt(using: adapter)
579 task = queue.sync { session.uploadTask(withStreamedRequest: urlRequest) }
584 throw AdaptError(error: error)
591 /// The request sent or to be sent to the server.
592 open override var request: URLRequest? {
593 if let request = super.request { return request }
595 guard let uploadable = originalTask as? Uploadable else { return nil }
598 case .data(_, let urlRequest), .file(_, let urlRequest), .stream(_, let urlRequest):
603 /// The progress of uploading the payload to the server for the upload request.
604 open var uploadProgress: Progress { return uploadDelegate.uploadProgress }
606 var uploadDelegate: UploadTaskDelegate { return delegate as! UploadTaskDelegate }
608 // MARK: Upload Progress
610 /// Sets a closure to be called periodically during the lifecycle of the `UploadRequest` as data is sent to
613 /// After the data is sent to the server, the `progress(queue:closure:)` APIs can be used to monitor the progress
614 /// of data being read from the server.
616 /// - parameter queue: The dispatch queue to execute the closure on.
617 /// - parameter closure: The code to be executed periodically as data is sent to the server.
619 /// - returns: The request.
621 open func uploadProgress(queue: DispatchQueue = DispatchQueue.main, closure: @escaping ProgressHandler) -> Self {
622 uploadDelegate.uploadProgressHandler = (closure, queue)
631 /// Specific type of `Request` that manages an underlying `URLSessionStreamTask`.
632 @available(iOS 9.0, macOS 10.11, tvOS 9.0, *)
633 open class StreamRequest: Request {
634 enum Streamable: TaskConvertible {
635 case stream(hostName: String, port: Int)
636 case netService(NetService)
638 func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask {
639 let task: URLSessionTask
642 case let .stream(hostName, port):
643 task = queue.sync { session.streamTask(withHostName: hostName, port: port) }
644 case let .netService(netService):
645 task = queue.sync { session.streamTask(with: netService) }