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 /// Types adopting the `URLConvertible` protocol can be used to construct URLs, which are then used to construct
29 public protocol URLConvertible {
30 /// Returns a URL that conforms to RFC 2396 or throws an `Error`.
32 /// - throws: An `Error` if the type cannot be converted to a `URL`.
34 /// - returns: A URL or throws an `Error`.
35 func asURL() throws -> URL
38 extension String: URLConvertible {
39 /// Returns a URL if `self` represents a valid URL string that conforms to RFC 2396 or throws an `AFError`.
41 /// - throws: An `AFError.invalidURL` if `self` is not a valid URL string.
43 /// - returns: A URL or throws an `AFError`.
44 public func asURL() throws -> URL {
45 guard let url = URL(string: self) else { throw AFError.invalidURL(url: self) }
50 extension URL: URLConvertible {
52 public func asURL() throws -> URL { return self }
55 extension URLComponents: URLConvertible {
56 /// Returns a URL if `url` is not nil, otherwise throws an `Error`.
58 /// - throws: An `AFError.invalidURL` if `url` is `nil`.
60 /// - returns: A URL or throws an `AFError`.
61 public func asURL() throws -> URL {
62 guard let url = url else { throw AFError.invalidURL(url: self) }
69 /// Types adopting the `URLRequestConvertible` protocol can be used to construct URL requests.
70 public protocol URLRequestConvertible {
71 /// Returns a URL request or throws if an `Error` was encountered.
73 /// - throws: An `Error` if the underlying `URLRequest` is `nil`.
75 /// - returns: A URL request.
76 func asURLRequest() throws -> URLRequest
79 extension URLRequestConvertible {
81 public var urlRequest: URLRequest? { return try? asURLRequest() }
84 extension URLRequest: URLRequestConvertible {
85 /// Returns a URL request or throws if an `Error` was encountered.
86 public func asURLRequest() throws -> URLRequest { return self }
91 extension URLRequest {
92 /// Creates an instance with the specified `method`, `urlString` and `headers`.
94 /// - parameter url: The URL.
95 /// - parameter method: The HTTP method.
96 /// - parameter headers: The HTTP headers. `nil` by default.
98 /// - returns: The new `URLRequest` instance.
99 public init(url: URLConvertible, method: HTTPMethod, headers: HTTPHeaders? = nil) throws {
100 let url = try url.asURL()
104 httpMethod = method.rawValue
106 if let headers = headers {
107 for (headerField, headerValue) in headers {
108 setValue(headerValue, forHTTPHeaderField: headerField)
113 func adapt(using adapter: RequestAdapter?) throws -> URLRequest {
114 guard let adapter = adapter else { return self }
115 return try adapter.adapt(self)
119 // MARK: - Data Request
121 /// Creates a `DataRequest` using the default `SessionManager` to retrieve the contents of the specified `url`,
122 /// `method`, `parameters`, `encoding` and `headers`.
124 /// - parameter url: The URL.
125 /// - parameter method: The HTTP method. `.get` by default.
126 /// - parameter parameters: The parameters. `nil` by default.
127 /// - parameter encoding: The parameter encoding. `URLEncoding.default` by default.
128 /// - parameter headers: The HTTP headers. `nil` by default.
130 /// - returns: The created `DataRequest`.
133 _ url: URLConvertible,
134 method: HTTPMethod = .get,
135 parameters: Parameters? = nil,
136 encoding: ParameterEncoding = URLEncoding.default,
137 headers: HTTPHeaders? = nil)
140 return SessionManager.default.request(
143 parameters: parameters,
149 /// Creates a `DataRequest` using the default `SessionManager` to retrieve the contents of a URL based on the
150 /// specified `urlRequest`.
152 /// - parameter urlRequest: The URL request
154 /// - returns: The created `DataRequest`.
156 public func request(_ urlRequest: URLRequestConvertible) -> DataRequest {
157 return SessionManager.default.request(urlRequest)
160 // MARK: - Download Request
164 /// Creates a `DownloadRequest` using the default `SessionManager` to retrieve the contents of the specified `url`,
165 /// `method`, `parameters`, `encoding`, `headers` and save them to the `destination`.
167 /// If `destination` is not specified, the contents will remain in the temporary location determined by the
168 /// underlying URL session.
170 /// - parameter url: The URL.
171 /// - parameter method: The HTTP method. `.get` by default.
172 /// - parameter parameters: The parameters. `nil` by default.
173 /// - parameter encoding: The parameter encoding. `URLEncoding.default` by default.
174 /// - parameter headers: The HTTP headers. `nil` by default.
175 /// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default.
177 /// - returns: The created `DownloadRequest`.
179 public func download(
180 _ url: URLConvertible,
181 method: HTTPMethod = .get,
182 parameters: Parameters? = nil,
183 encoding: ParameterEncoding = URLEncoding.default,
184 headers: HTTPHeaders? = nil,
185 to destination: DownloadRequest.DownloadFileDestination? = nil)
188 return SessionManager.default.download(
191 parameters: parameters,
198 /// Creates a `DownloadRequest` using the default `SessionManager` to retrieve the contents of a URL based on the
199 /// specified `urlRequest` and save them to the `destination`.
201 /// If `destination` is not specified, the contents will remain in the temporary location determined by the
202 /// underlying URL session.
204 /// - parameter urlRequest: The URL request.
205 /// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default.
207 /// - returns: The created `DownloadRequest`.
209 public func download(
210 _ urlRequest: URLRequestConvertible,
211 to destination: DownloadRequest.DownloadFileDestination? = nil)
214 return SessionManager.default.download(urlRequest, to: destination)
219 /// Creates a `DownloadRequest` using the default `SessionManager` from the `resumeData` produced from a
220 /// previous request cancellation to retrieve the contents of the original request and save them to the `destination`.
222 /// If `destination` is not specified, the contents will remain in the temporary location determined by the
223 /// underlying URL session.
225 /// On the latest release of all the Apple platforms (iOS 10, macOS 10.12, tvOS 10, watchOS 3), `resumeData` is broken
226 /// on background URL session configurations. There's an underlying bug in the `resumeData` generation logic where the
227 /// data is written incorrectly and will always fail to resume the download. For more information about the bug and
228 /// possible workarounds, please refer to the following Stack Overflow post:
230 /// - http://stackoverflow.com/a/39347461/1342462
232 /// - parameter resumeData: The resume data. This is an opaque data blob produced by `URLSessionDownloadTask`
233 /// when a task is cancelled. See `URLSession -downloadTask(withResumeData:)` for additional
235 /// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default.
237 /// - returns: The created `DownloadRequest`.
239 public func download(
240 resumingWith resumeData: Data,
241 to destination: DownloadRequest.DownloadFileDestination? = nil)
244 return SessionManager.default.download(resumingWith: resumeData, to: destination)
247 // MARK: - Upload Request
251 /// Creates an `UploadRequest` using the default `SessionManager` from the specified `url`, `method` and `headers`
252 /// for uploading the `file`.
254 /// - parameter file: The file to upload.
255 /// - parameter url: The URL.
256 /// - parameter method: The HTTP method. `.post` by default.
257 /// - parameter headers: The HTTP headers. `nil` by default.
259 /// - returns: The created `UploadRequest`.
263 to url: URLConvertible,
264 method: HTTPMethod = .post,
265 headers: HTTPHeaders? = nil)
268 return SessionManager.default.upload(fileURL, to: url, method: method, headers: headers)
271 /// Creates a `UploadRequest` using the default `SessionManager` from the specified `urlRequest` for
272 /// uploading the `file`.
274 /// - parameter file: The file to upload.
275 /// - parameter urlRequest: The URL request.
277 /// - returns: The created `UploadRequest`.
279 public func upload(_ fileURL: URL, with urlRequest: URLRequestConvertible) -> UploadRequest {
280 return SessionManager.default.upload(fileURL, with: urlRequest)
285 /// Creates an `UploadRequest` using the default `SessionManager` from the specified `url`, `method` and `headers`
286 /// for uploading the `data`.
288 /// - parameter data: The data to upload.
289 /// - parameter url: The URL.
290 /// - parameter method: The HTTP method. `.post` by default.
291 /// - parameter headers: The HTTP headers. `nil` by default.
293 /// - returns: The created `UploadRequest`.
297 to url: URLConvertible,
298 method: HTTPMethod = .post,
299 headers: HTTPHeaders? = nil)
302 return SessionManager.default.upload(data, to: url, method: method, headers: headers)
305 /// Creates an `UploadRequest` using the default `SessionManager` from the specified `urlRequest` for
306 /// uploading the `data`.
308 /// - parameter data: The data to upload.
309 /// - parameter urlRequest: The URL request.
311 /// - returns: The created `UploadRequest`.
313 public func upload(_ data: Data, with urlRequest: URLRequestConvertible) -> UploadRequest {
314 return SessionManager.default.upload(data, with: urlRequest)
319 /// Creates an `UploadRequest` using the default `SessionManager` from the specified `url`, `method` and `headers`
320 /// for uploading the `stream`.
322 /// - parameter stream: The stream to upload.
323 /// - parameter url: The URL.
324 /// - parameter method: The HTTP method. `.post` by default.
325 /// - parameter headers: The HTTP headers. `nil` by default.
327 /// - returns: The created `UploadRequest`.
330 _ stream: InputStream,
331 to url: URLConvertible,
332 method: HTTPMethod = .post,
333 headers: HTTPHeaders? = nil)
336 return SessionManager.default.upload(stream, to: url, method: method, headers: headers)
339 /// Creates an `UploadRequest` using the default `SessionManager` from the specified `urlRequest` for
340 /// uploading the `stream`.
342 /// - parameter urlRequest: The URL request.
343 /// - parameter stream: The stream to upload.
345 /// - returns: The created `UploadRequest`.
347 public func upload(_ stream: InputStream, with urlRequest: URLRequestConvertible) -> UploadRequest {
348 return SessionManager.default.upload(stream, with: urlRequest)
351 // MARK: MultipartFormData
353 /// Encodes `multipartFormData` using `encodingMemoryThreshold` with the default `SessionManager` and calls
354 /// `encodingCompletion` with new `UploadRequest` using the `url`, `method` and `headers`.
356 /// It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative
357 /// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most
358 /// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to
359 /// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory
360 /// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be
361 /// used for larger payloads such as video content.
363 /// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory
364 /// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`,
365 /// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk
366 /// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding
367 /// technique was used.
369 /// - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`.
370 /// - parameter encodingMemoryThreshold: The encoding memory threshold in bytes.
371 /// `multipartFormDataEncodingMemoryThreshold` by default.
372 /// - parameter url: The URL.
373 /// - parameter method: The HTTP method. `.post` by default.
374 /// - parameter headers: The HTTP headers. `nil` by default.
375 /// - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete.
377 multipartFormData: @escaping (MultipartFormData) -> Void,
378 usingThreshold encodingMemoryThreshold: UInt64 = SessionManager.multipartFormDataEncodingMemoryThreshold,
379 to url: URLConvertible,
380 method: HTTPMethod = .post,
381 headers: HTTPHeaders? = nil,
382 encodingCompletion: ((SessionManager.MultipartFormDataEncodingResult) -> Void)?)
384 return SessionManager.default.upload(
385 multipartFormData: multipartFormData,
386 usingThreshold: encodingMemoryThreshold,
390 encodingCompletion: encodingCompletion
394 /// Encodes `multipartFormData` using `encodingMemoryThreshold` and the default `SessionManager` and
395 /// calls `encodingCompletion` with new `UploadRequest` using the `urlRequest`.
397 /// It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative
398 /// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most
399 /// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to
400 /// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory
401 /// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be
402 /// used for larger payloads such as video content.
404 /// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory
405 /// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`,
406 /// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk
407 /// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding
408 /// technique was used.
410 /// - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`.
411 /// - parameter encodingMemoryThreshold: The encoding memory threshold in bytes.
412 /// `multipartFormDataEncodingMemoryThreshold` by default.
413 /// - parameter urlRequest: The URL request.
414 /// - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete.
416 multipartFormData: @escaping (MultipartFormData) -> Void,
417 usingThreshold encodingMemoryThreshold: UInt64 = SessionManager.multipartFormDataEncodingMemoryThreshold,
418 with urlRequest: URLRequestConvertible,
419 encodingCompletion: ((SessionManager.MultipartFormDataEncodingResult) -> Void)?)
421 return SessionManager.default.upload(
422 multipartFormData: multipartFormData,
423 usingThreshold: encodingMemoryThreshold,
425 encodingCompletion: encodingCompletion
431 // MARK: - Stream Request
433 // MARK: Hostname and Port
435 /// Creates a `StreamRequest` using the default `SessionManager` for bidirectional streaming with the `hostname`
438 /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
440 /// - parameter hostName: The hostname of the server to connect to.
441 /// - parameter port: The port of the server to connect to.
443 /// - returns: The created `StreamRequest`.
445 @available(iOS 9.0, macOS 10.11, tvOS 9.0, *)
446 public func stream(withHostName hostName: String, port: Int) -> StreamRequest {
447 return SessionManager.default.stream(withHostName: hostName, port: port)
452 /// Creates a `StreamRequest` using the default `SessionManager` for bidirectional streaming with the `netService`.
454 /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
456 /// - parameter netService: The net service used to identify the endpoint.
458 /// - returns: The created `StreamRequest`.
460 @available(iOS 9.0, macOS 10.11, tvOS 9.0, *)
461 public func stream(with netService: NetService) -> StreamRequest {
462 return SessionManager.default.stream(with: netService)