added iOS source code
[wl-app.git] / iOS / Pods / Alamofire / Source / Alamofire.swift
1 //
2 //  Alamofire.swift
3 //
4 //  Copyright (c) 2014-2017 Alamofire Software Foundation (http://alamofire.org/)
5 //
6 //  Permission is hereby granted, free of charge, to any person obtaining a copy
7 //  of this software and associated documentation files (the "Software"), to deal
8 //  in the Software without restriction, including without limitation the rights
9 //  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 //  copies of the Software, and to permit persons to whom the Software is
11 //  furnished to do so, subject to the following conditions:
12 //
13 //  The above copyright notice and this permission notice shall be included in
14 //  all copies or substantial portions of the Software.
15 //
16 //  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 //  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 //  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 //  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 //  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 //  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 //  THE SOFTWARE.
23 //
24
25 import Foundation
26
27 /// Types adopting the `URLConvertible` protocol can be used to construct URLs, which are then used to construct
28 /// URL requests.
29 public protocol URLConvertible {
30     /// Returns a URL that conforms to RFC 2396 or throws an `Error`.
31     ///
32     /// - throws: An `Error` if the type cannot be converted to a `URL`.
33     ///
34     /// - returns: A URL or throws an `Error`.
35     func asURL() throws -> URL
36 }
37
38 extension String: URLConvertible {
39     /// Returns a URL if `self` represents a valid URL string that conforms to RFC 2396 or throws an `AFError`.
40     ///
41     /// - throws: An `AFError.invalidURL` if `self` is not a valid URL string.
42     ///
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) }
46         return url
47     }
48 }
49
50 extension URL: URLConvertible {
51     /// Returns self.
52     public func asURL() throws -> URL { return self }
53 }
54
55 extension URLComponents: URLConvertible {
56     /// Returns a URL if `url` is not nil, otherwise throws an `Error`.
57     ///
58     /// - throws: An `AFError.invalidURL` if `url` is `nil`.
59     ///
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) }
63         return url
64     }
65 }
66
67 // MARK: -
68
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.
72     ///
73     /// - throws: An `Error` if the underlying `URLRequest` is `nil`.
74     ///
75     /// - returns: A URL request.
76     func asURLRequest() throws -> URLRequest
77 }
78
79 extension URLRequestConvertible {
80     /// The URL request.
81     public var urlRequest: URLRequest? { return try? asURLRequest() }
82 }
83
84 extension URLRequest: URLRequestConvertible {
85     /// Returns a URL request or throws if an `Error` was encountered.
86     public func asURLRequest() throws -> URLRequest { return self }
87 }
88
89 // MARK: -
90
91 extension URLRequest {
92     /// Creates an instance with the specified `method`, `urlString` and `headers`.
93     ///
94     /// - parameter url:     The URL.
95     /// - parameter method:  The HTTP method.
96     /// - parameter headers: The HTTP headers. `nil` by default.
97     ///
98     /// - returns: The new `URLRequest` instance.
99     public init(url: URLConvertible, method: HTTPMethod, headers: HTTPHeaders? = nil) throws {
100         let url = try url.asURL()
101
102         self.init(url: url)
103
104         httpMethod = method.rawValue
105
106         if let headers = headers {
107             for (headerField, headerValue) in headers {
108                 setValue(headerValue, forHTTPHeaderField: headerField)
109             }
110         }
111     }
112
113     func adapt(using adapter: RequestAdapter?) throws -> URLRequest {
114         guard let adapter = adapter else { return self }
115         return try adapter.adapt(self)
116     }
117 }
118
119 // MARK: - Data Request
120
121 /// Creates a `DataRequest` using the default `SessionManager` to retrieve the contents of the specified `url`,
122 /// `method`, `parameters`, `encoding` and `headers`.
123 ///
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.
129 ///
130 /// - returns: The created `DataRequest`.
131 @discardableResult
132 public func request(
133     _ url: URLConvertible,
134     method: HTTPMethod = .get,
135     parameters: Parameters? = nil,
136     encoding: ParameterEncoding = URLEncoding.default,
137     headers: HTTPHeaders? = nil)
138     -> DataRequest
139 {
140     return SessionManager.default.request(
141         url,
142         method: method,
143         parameters: parameters,
144         encoding: encoding,
145         headers: headers
146     )
147 }
148
149 /// Creates a `DataRequest` using the default `SessionManager` to retrieve the contents of a URL based on the
150 /// specified `urlRequest`.
151 ///
152 /// - parameter urlRequest: The URL request
153 ///
154 /// - returns: The created `DataRequest`.
155 @discardableResult
156 public func request(_ urlRequest: URLRequestConvertible) -> DataRequest {
157     return SessionManager.default.request(urlRequest)
158 }
159
160 // MARK: - Download Request
161
162 // MARK: URL Request
163
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`.
166 ///
167 /// If `destination` is not specified, the contents will remain in the temporary location determined by the
168 /// underlying URL session.
169 ///
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.
176 ///
177 /// - returns: The created `DownloadRequest`.
178 @discardableResult
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)
186     -> DownloadRequest
187 {
188     return SessionManager.default.download(
189         url,
190         method: method,
191         parameters: parameters,
192         encoding: encoding,
193         headers: headers,
194         to: destination
195     )
196 }
197
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`.
200 ///
201 /// If `destination` is not specified, the contents will remain in the temporary location determined by the
202 /// underlying URL session.
203 ///
204 /// - parameter urlRequest:  The URL request.
205 /// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default.
206 ///
207 /// - returns: The created `DownloadRequest`.
208 @discardableResult
209 public func download(
210     _ urlRequest: URLRequestConvertible,
211     to destination: DownloadRequest.DownloadFileDestination? = nil)
212     -> DownloadRequest
213 {
214     return SessionManager.default.download(urlRequest, to: destination)
215 }
216
217 // MARK: Resume Data
218
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`.
221 ///
222 /// If `destination` is not specified, the contents will remain in the temporary location determined by the
223 /// underlying URL session.
224 ///
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:
229 ///
230 ///    - http://stackoverflow.com/a/39347461/1342462
231 ///
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
234 ///                          information.
235 /// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default.
236 ///
237 /// - returns: The created `DownloadRequest`.
238 @discardableResult
239 public func download(
240     resumingWith resumeData: Data,
241     to destination: DownloadRequest.DownloadFileDestination? = nil)
242     -> DownloadRequest
243 {
244     return SessionManager.default.download(resumingWith: resumeData, to: destination)
245 }
246
247 // MARK: - Upload Request
248
249 // MARK: File
250
251 /// Creates an `UploadRequest` using the default `SessionManager` from the specified `url`, `method` and `headers`
252 /// for uploading the `file`.
253 ///
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.
258 ///
259 /// - returns: The created `UploadRequest`.
260 @discardableResult
261 public func upload(
262     _ fileURL: URL,
263     to url: URLConvertible,
264     method: HTTPMethod = .post,
265     headers: HTTPHeaders? = nil)
266     -> UploadRequest
267 {
268     return SessionManager.default.upload(fileURL, to: url, method: method, headers: headers)
269 }
270
271 /// Creates a `UploadRequest` using the default `SessionManager` from the specified `urlRequest` for
272 /// uploading the `file`.
273 ///
274 /// - parameter file:       The file to upload.
275 /// - parameter urlRequest: The URL request.
276 ///
277 /// - returns: The created `UploadRequest`.
278 @discardableResult
279 public func upload(_ fileURL: URL, with urlRequest: URLRequestConvertible) -> UploadRequest {
280     return SessionManager.default.upload(fileURL, with: urlRequest)
281 }
282
283 // MARK: Data
284
285 /// Creates an `UploadRequest` using the default `SessionManager` from the specified `url`, `method` and `headers`
286 /// for uploading the `data`.
287 ///
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.
292 ///
293 /// - returns: The created `UploadRequest`.
294 @discardableResult
295 public func upload(
296     _ data: Data,
297     to url: URLConvertible,
298     method: HTTPMethod = .post,
299     headers: HTTPHeaders? = nil)
300     -> UploadRequest
301 {
302     return SessionManager.default.upload(data, to: url, method: method, headers: headers)
303 }
304
305 /// Creates an `UploadRequest` using the default `SessionManager` from the specified `urlRequest` for
306 /// uploading the `data`.
307 ///
308 /// - parameter data:       The data to upload.
309 /// - parameter urlRequest: The URL request.
310 ///
311 /// - returns: The created `UploadRequest`.
312 @discardableResult
313 public func upload(_ data: Data, with urlRequest: URLRequestConvertible) -> UploadRequest {
314     return SessionManager.default.upload(data, with: urlRequest)
315 }
316
317 // MARK: InputStream
318
319 /// Creates an `UploadRequest` using the default `SessionManager` from the specified `url`, `method` and `headers`
320 /// for uploading the `stream`.
321 ///
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.
326 ///
327 /// - returns: The created `UploadRequest`.
328 @discardableResult
329 public func upload(
330     _ stream: InputStream,
331     to url: URLConvertible,
332     method: HTTPMethod = .post,
333     headers: HTTPHeaders? = nil)
334     -> UploadRequest
335 {
336     return SessionManager.default.upload(stream, to: url, method: method, headers: headers)
337 }
338
339 /// Creates an `UploadRequest` using the default `SessionManager` from the specified `urlRequest` for
340 /// uploading the `stream`.
341 ///
342 /// - parameter urlRequest: The URL request.
343 /// - parameter stream:     The stream to upload.
344 ///
345 /// - returns: The created `UploadRequest`.
346 @discardableResult
347 public func upload(_ stream: InputStream, with urlRequest: URLRequestConvertible) -> UploadRequest {
348     return SessionManager.default.upload(stream, with: urlRequest)
349 }
350
351 // MARK: MultipartFormData
352
353 /// Encodes `multipartFormData` using `encodingMemoryThreshold` with the default `SessionManager` and calls
354 /// `encodingCompletion` with new `UploadRequest` using the `url`, `method` and `headers`.
355 ///
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.
362 ///
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.
368 ///
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.
376 public func upload(
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)?)
383 {
384     return SessionManager.default.upload(
385         multipartFormData: multipartFormData,
386         usingThreshold: encodingMemoryThreshold,
387         to: url,
388         method: method,
389         headers: headers,
390         encodingCompletion: encodingCompletion
391     )
392 }
393
394 /// Encodes `multipartFormData` using `encodingMemoryThreshold` and the default `SessionManager` and
395 /// calls `encodingCompletion` with new `UploadRequest` using the `urlRequest`.
396 ///
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.
403 ///
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.
409 ///
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.
415 public func upload(
416     multipartFormData: @escaping (MultipartFormData) -> Void,
417     usingThreshold encodingMemoryThreshold: UInt64 = SessionManager.multipartFormDataEncodingMemoryThreshold,
418     with urlRequest: URLRequestConvertible,
419     encodingCompletion: ((SessionManager.MultipartFormDataEncodingResult) -> Void)?)
420 {
421     return SessionManager.default.upload(
422         multipartFormData: multipartFormData,
423         usingThreshold: encodingMemoryThreshold,
424         with: urlRequest,
425         encodingCompletion: encodingCompletion
426     )
427 }
428
429 #if !os(watchOS)
430
431 // MARK: - Stream Request
432
433 // MARK: Hostname and Port
434
435 /// Creates a `StreamRequest` using the default `SessionManager` for bidirectional streaming with the `hostname`
436 /// and `port`.
437 ///
438 /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
439 ///
440 /// - parameter hostName: The hostname of the server to connect to.
441 /// - parameter port:     The port of the server to connect to.
442 ///
443 /// - returns: The created `StreamRequest`.
444 @discardableResult
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)
448 }
449
450 // MARK: NetService
451
452 /// Creates a `StreamRequest` using the default `SessionManager` for bidirectional streaming with the `netService`.
453 ///
454 /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
455 ///
456 /// - parameter netService: The net service used to identify the endpoint.
457 ///
458 /// - returns: The created `StreamRequest`.
459 @discardableResult
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)
463 }
464
465 #endif