Alamofire.swift 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  1. //
  2. // Alamofire.swift
  3. //
  4. // Copyright (c) 2014-2018 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. import Foundation
  25. /// Types adopting the `URLConvertible` protocol can be used to construct URLs, which are then used to construct
  26. /// URL requests.
  27. public protocol URLConvertible {
  28. /// Returns a URL that conforms to RFC 2396 or throws an `Error`.
  29. ///
  30. /// - throws: An `Error` if the type cannot be converted to a `URL`.
  31. ///
  32. /// - returns: A URL or throws an `Error`.
  33. func asURL() throws -> URL
  34. }
  35. extension String: URLConvertible {
  36. /// Returns a URL if `self` represents a valid URL string that conforms to RFC 2396 or throws an `AFError`.
  37. ///
  38. /// - throws: An `AFError.invalidURL` if `self` is not a valid URL string.
  39. ///
  40. /// - returns: A URL or throws an `AFError`.
  41. public func asURL() throws -> URL {
  42. guard let url = URL(string: self) else { throw AFError.invalidURL(url: self) }
  43. return url
  44. }
  45. }
  46. extension URL: URLConvertible {
  47. /// Returns self.
  48. public func asURL() throws -> URL { return self }
  49. }
  50. extension URLComponents: URLConvertible {
  51. /// Returns a URL if `url` is not nil, otherwise throws an `Error`.
  52. ///
  53. /// - throws: An `AFError.invalidURL` if `url` is `nil`.
  54. ///
  55. /// - returns: A URL or throws an `AFError`.
  56. public func asURL() throws -> URL {
  57. guard let url = url else { throw AFError.invalidURL(url: self) }
  58. return url
  59. }
  60. }
  61. // MARK: -
  62. /// Types adopting the `URLRequestConvertible` protocol can be used to construct URL requests.
  63. public protocol URLRequestConvertible {
  64. /// Returns a URL request or throws if an `Error` was encountered.
  65. ///
  66. /// - throws: An `Error` if the underlying `URLRequest` is `nil`.
  67. ///
  68. /// - returns: A URL request.
  69. func asURLRequest() throws -> URLRequest
  70. }
  71. extension URLRequestConvertible {
  72. /// The URL request.
  73. public var urlRequest: URLRequest? { return try? asURLRequest() }
  74. }
  75. extension URLRequest: URLRequestConvertible {
  76. /// Returns a URL request or throws if an `Error` was encountered.
  77. public func asURLRequest() throws -> URLRequest { return self }
  78. }
  79. // MARK: -
  80. extension URLRequest {
  81. /// Creates an instance with the specified `method`, `urlString` and `headers`.
  82. ///
  83. /// - parameter url: The URL.
  84. /// - parameter method: The HTTP method.
  85. /// - parameter headers: The HTTP headers. `nil` by default.
  86. ///
  87. /// - returns: The new `URLRequest` instance.
  88. public init(url: URLConvertible, method: HTTPMethod, headers: HTTPHeaders? = nil) throws {
  89. let url = try url.asURL()
  90. self.init(url: url)
  91. httpMethod = method.rawValue
  92. if let headers = headers {
  93. for (headerField, headerValue) in headers {
  94. setValue(headerValue, forHTTPHeaderField: headerField)
  95. }
  96. }
  97. }
  98. func adapt(using adapter: RequestAdapter?) throws -> URLRequest {
  99. guard let adapter = adapter else { return self }
  100. return try adapter.adapt(self)
  101. }
  102. }
  103. // MARK: - Data Request
  104. /// Creates a `DataRequest` using the default `SessionManager` to retrieve the contents of the specified `url`,
  105. /// `method`, `parameters`, `encoding` and `headers`.
  106. ///
  107. /// - parameter url: The URL.
  108. /// - parameter method: The HTTP method. `.get` by default.
  109. /// - parameter parameters: The parameters. `nil` by default.
  110. /// - parameter encoding: The parameter encoding. `URLEncoding.default` by default.
  111. /// - parameter headers: The HTTP headers. `nil` by default.
  112. ///
  113. /// - returns: The created `DataRequest`.
  114. @discardableResult
  115. public func request(_ url: URLConvertible,
  116. method: HTTPMethod = .get,
  117. parameters: Parameters? = nil,
  118. encoding: ParameterEncoding = URLEncoding.default,
  119. headers: HTTPHeaders? = nil) -> DataRequest {
  120. return SessionManager.default.request(url,
  121. method: method,
  122. parameters: parameters,
  123. encoding: encoding,
  124. headers: headers)
  125. }
  126. /// Creates a `DataRequest` using the default `SessionManager` to retrieve the contents of a URL based on the
  127. /// specified `urlRequest`.
  128. ///
  129. /// - parameter urlRequest: The URL request
  130. ///
  131. /// - returns: The created `DataRequest`.
  132. @discardableResult
  133. public func request(_ urlRequest: URLRequestConvertible) -> DataRequest {
  134. return SessionManager.default.request(urlRequest)
  135. }
  136. // MARK: - Download Request
  137. // MARK: URL Request
  138. /// Creates a `DownloadRequest` using the default `SessionManager` to retrieve the contents of the specified `url`,
  139. /// `method`, `parameters`, `encoding`, `headers` and save them to the `destination`.
  140. ///
  141. /// If `destination` is not specified, the contents will remain in the temporary location determined by the
  142. /// underlying URL session.
  143. ///
  144. /// - parameter url: The URL.
  145. /// - parameter method: The HTTP method. `.get` by default.
  146. /// - parameter parameters: The parameters. `nil` by default.
  147. /// - parameter encoding: The parameter encoding. `URLEncoding.default` by default.
  148. /// - parameter headers: The HTTP headers. `nil` by default.
  149. /// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default.
  150. ///
  151. /// - returns: The created `DownloadRequest`.
  152. @discardableResult
  153. public func download(
  154. _ url: URLConvertible,
  155. method: HTTPMethod = .get,
  156. parameters: Parameters? = nil,
  157. encoding: ParameterEncoding = URLEncoding.default,
  158. headers: HTTPHeaders? = nil,
  159. to destination: DownloadRequest.Destination? = nil)
  160. -> DownloadRequest
  161. {
  162. return SessionManager.default.download(
  163. url,
  164. method: method,
  165. parameters: parameters,
  166. encoding: encoding,
  167. headers: headers,
  168. to: destination
  169. )
  170. }
  171. /// Creates a `DownloadRequest` using the default `SessionManager` to retrieve the contents of a URL based on the
  172. /// specified `urlRequest` and save them to the `destination`.
  173. ///
  174. /// If `destination` is not specified, the contents will remain in the temporary location determined by the
  175. /// underlying URL session.
  176. ///
  177. /// - parameter urlRequest: The URL request.
  178. /// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default.
  179. ///
  180. /// - returns: The created `DownloadRequest`.
  181. @discardableResult
  182. public func download(
  183. _ urlRequest: URLRequestConvertible,
  184. to destination: DownloadRequest.Destination? = nil)
  185. -> DownloadRequest
  186. {
  187. return SessionManager.default.download(urlRequest, to: destination)
  188. }
  189. // MARK: Resume Data
  190. /// Creates a `DownloadRequest` using the default `SessionManager` from the `resumeData` produced from a
  191. /// previous request cancellation to retrieve the contents of the original request and save them to the `destination`.
  192. ///
  193. /// If `destination` is not specified, the contents will remain in the temporary location determined by the
  194. /// underlying URL session.
  195. ///
  196. /// On some versions of all Apple platforms (iOS 10 - 10.2, macOS 10.12 - 10.12.2, tvOS 10 - 10.1, watchOS 3 - 3.1.1),
  197. /// `resumeData` is broken on background URL session configurations. There's an underlying bug in the `resumeData`
  198. /// generation logic where the data is written incorrectly and will always fail to resume the download. For more
  199. /// information about the bug and possible workarounds, please refer to the following Stack Overflow post:
  200. ///
  201. /// - http://stackoverflow.com/a/39347461/1342462
  202. ///
  203. /// - parameter resumeData: The resume data. This is an opaque data blob produced by `URLSessionDownloadTask`
  204. /// when a task is cancelled. See `URLSession -downloadTask(withResumeData:)` for additional
  205. /// information.
  206. /// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default.
  207. ///
  208. /// - returns: The created `DownloadRequest`.
  209. @discardableResult
  210. public func download(
  211. resumingWith resumeData: Data,
  212. to destination: DownloadRequest.Destination? = nil)
  213. -> DownloadRequest
  214. {
  215. return SessionManager.default.download(resumingWith: resumeData, to: destination)
  216. }
  217. // MARK: - Upload Request
  218. // MARK: File
  219. /// Creates an `UploadRequest` using the default `SessionManager` from the specified `url`, `method` and `headers`
  220. /// for uploading the `file`.
  221. ///
  222. /// - parameter file: The file to upload.
  223. /// - parameter url: The URL.
  224. /// - parameter method: The HTTP method. `.post` by default.
  225. /// - parameter headers: The HTTP headers. `nil` by default.
  226. ///
  227. /// - returns: The created `UploadRequest`.
  228. @discardableResult
  229. public func upload(
  230. _ fileURL: URL,
  231. to url: URLConvertible,
  232. method: HTTPMethod = .post,
  233. headers: HTTPHeaders? = nil)
  234. -> UploadRequest
  235. {
  236. return SessionManager.default.upload(fileURL, to: url, method: method, headers: headers)
  237. }
  238. /// Creates a `UploadRequest` using the default `SessionManager` from the specified `urlRequest` for
  239. /// uploading the `file`.
  240. ///
  241. /// - parameter file: The file to upload.
  242. /// - parameter urlRequest: The URL request.
  243. ///
  244. /// - returns: The created `UploadRequest`.
  245. @discardableResult
  246. public func upload(_ fileURL: URL, with urlRequest: URLRequestConvertible) -> UploadRequest {
  247. return SessionManager.default.upload(fileURL, with: urlRequest)
  248. }
  249. // MARK: Data
  250. /// Creates an `UploadRequest` using the default `SessionManager` from the specified `url`, `method` and `headers`
  251. /// for uploading the `data`.
  252. ///
  253. /// - parameter data: The data to upload.
  254. /// - parameter url: The URL.
  255. /// - parameter method: The HTTP method. `.post` by default.
  256. /// - parameter headers: The HTTP headers. `nil` by default.
  257. ///
  258. /// - returns: The created `UploadRequest`.
  259. @discardableResult
  260. public func upload(
  261. _ data: Data,
  262. to url: URLConvertible,
  263. method: HTTPMethod = .post,
  264. headers: HTTPHeaders? = nil)
  265. -> UploadRequest
  266. {
  267. return SessionManager.default.upload(data, to: url, method: method, headers: headers)
  268. }
  269. /// Creates an `UploadRequest` using the default `SessionManager` from the specified `urlRequest` for
  270. /// uploading the `data`.
  271. ///
  272. /// - parameter data: The data to upload.
  273. /// - parameter urlRequest: The URL request.
  274. ///
  275. /// - returns: The created `UploadRequest`.
  276. @discardableResult
  277. public func upload(_ data: Data, with urlRequest: URLRequestConvertible) -> UploadRequest {
  278. return SessionManager.default.upload(data, with: urlRequest)
  279. }
  280. // MARK: InputStream
  281. /// Creates an `UploadRequest` using the default `SessionManager` from the specified `url`, `method` and `headers`
  282. /// for uploading the `stream`.
  283. ///
  284. /// - parameter stream: The stream to upload.
  285. /// - parameter url: The URL.
  286. /// - parameter method: The HTTP method. `.post` by default.
  287. /// - parameter headers: The HTTP headers. `nil` by default.
  288. ///
  289. /// - returns: The created `UploadRequest`.
  290. @discardableResult
  291. public func upload(
  292. _ stream: InputStream,
  293. to url: URLConvertible,
  294. method: HTTPMethod = .post,
  295. headers: HTTPHeaders? = nil)
  296. -> UploadRequest
  297. {
  298. return SessionManager.default.upload(stream, to: url, method: method, headers: headers)
  299. }
  300. /// Creates an `UploadRequest` using the default `SessionManager` from the specified `urlRequest` for
  301. /// uploading the `stream`.
  302. ///
  303. /// - parameter urlRequest: The URL request.
  304. /// - parameter stream: The stream to upload.
  305. ///
  306. /// - returns: The created `UploadRequest`.
  307. @discardableResult
  308. public func upload(_ stream: InputStream, with urlRequest: URLRequestConvertible) -> UploadRequest {
  309. return SessionManager.default.upload(stream, with: urlRequest)
  310. }
  311. // MARK: MultipartFormData
  312. /// Encodes `multipartFormData` using `encodingMemoryThreshold` with the default `SessionManager` and calls
  313. /// `encodingCompletion` with new `UploadRequest` using the `url`, `method` and `headers`.
  314. ///
  315. /// It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative
  316. /// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most
  317. /// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to
  318. /// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory
  319. /// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be
  320. /// used for larger payloads such as video content.
  321. ///
  322. /// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory
  323. /// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`,
  324. /// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk
  325. /// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding
  326. /// technique was used.
  327. ///
  328. /// - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`.
  329. /// - parameter encodingMemoryThreshold: The encoding memory threshold in bytes.
  330. /// `multipartFormDataEncodingMemoryThreshold` by default.
  331. /// - parameter url: The URL.
  332. /// - parameter method: The HTTP method. `.post` by default.
  333. /// - parameter headers: The HTTP headers. `nil` by default.
  334. /// - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete.
  335. public func upload(
  336. multipartFormData: @escaping (MultipartFormData) -> Void,
  337. usingThreshold encodingMemoryThreshold: UInt64 = MultipartUpload.multipartFormDataEncodingMemoryThreshold,
  338. to url: URLConvertible,
  339. method: HTTPMethod = .post,
  340. headers: HTTPHeaders? = nil) -> UploadRequest
  341. {
  342. return SessionManager.default.upload(
  343. multipartFormData: multipartFormData,
  344. usingThreshold: encodingMemoryThreshold,
  345. to: url,
  346. method: method,
  347. headers: headers
  348. )
  349. }
  350. /// Encodes `multipartFormData` using `encodingMemoryThreshold` and the default `SessionManager` and
  351. /// calls `encodingCompletion` with new `UploadRequest` using the `urlRequest`.
  352. ///
  353. /// It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative
  354. /// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most
  355. /// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to
  356. /// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory
  357. /// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be
  358. /// used for larger payloads such as video content.
  359. ///
  360. /// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory
  361. /// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`,
  362. /// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk
  363. /// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding
  364. /// technique was used.
  365. ///
  366. /// - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`.
  367. /// - parameter encodingMemoryThreshold: The encoding memory threshold in bytes.
  368. /// `multipartFormDataEncodingMemoryThreshold` by default.
  369. /// - parameter urlRequest: The URL request.
  370. /// - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete.
  371. public func upload(
  372. multipartFormData: @escaping (MultipartFormData) -> Void,
  373. usingThreshold encodingMemoryThreshold: UInt64 = MultipartUpload.multipartFormDataEncodingMemoryThreshold,
  374. with urlRequest: URLRequestConvertible) -> UploadRequest
  375. {
  376. return SessionManager.default.upload(
  377. multipartFormData: multipartFormData,
  378. usingThreshold: encodingMemoryThreshold,
  379. with: urlRequest
  380. )
  381. }