Alamofire.swift 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  1. //
  2. // Alamofire.swift
  3. //
  4. // Copyright (c) 2014-2016 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, otherise 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. /// The URL request.
  65. var urlRequest: URLRequest? { get }
  66. /// Returns a URL request or throws if an `Error` was encountered.
  67. ///
  68. /// - throws: An `Error` if the underlying `URLRequest` is `nil`.
  69. ///
  70. /// - returns: A URL request.
  71. func asURLRequest() throws -> URLRequest
  72. }
  73. extension URLRequestConvertible {
  74. /// The URL request.
  75. public var urlRequest: URLRequest? { return try? asURLRequest() }
  76. }
  77. extension URLRequest: URLRequestConvertible {
  78. /// Returns a URL request or throws if an `Error` was encountered.
  79. public func asURLRequest() throws -> URLRequest { return self }
  80. }
  81. // MARK: -
  82. extension URLRequest {
  83. /// Creates an instance with the specified `method`, `urlString` and `headers`.
  84. ///
  85. /// - parameter url: The URL.
  86. /// - parameter method: The HTTP method.
  87. /// - parameter headers: The HTTP headers. `nil` by default.
  88. ///
  89. /// - returns: The new `URLRequest` instance.
  90. public init(url: URLConvertible, method: HTTPMethod, headers: HTTPHeaders? = nil) throws {
  91. let url = try url.asURL()
  92. self.init(url: url)
  93. httpMethod = method.rawValue
  94. if let headers = headers {
  95. for (headerField, headerValue) in headers {
  96. setValue(headerValue, forHTTPHeaderField: headerField)
  97. }
  98. }
  99. }
  100. func adapt(using adapter: RequestAdapter?) throws -> URLRequest {
  101. guard let adapter = adapter else { return self }
  102. return try adapter.adapt(self)
  103. }
  104. }
  105. // MARK: - Data Request
  106. /// Creates a `DataRequest` using the default `SessionManager` to retrieve the contents of the specified `url`,
  107. /// `method`, `parameters`, `encoding` and `headers`.
  108. ///
  109. /// - parameter url: The URL.
  110. /// - parameter method: The HTTP method. `.get` by default.
  111. /// - parameter parameters: The parameters. `nil` by default.
  112. /// - parameter encoding: The parameter encoding. `URLEncoding.default` by default.
  113. /// - parameter headers: The HTTP headers. `nil` by default.
  114. ///
  115. /// - returns: The created `DataRequest`.
  116. @discardableResult
  117. public func request(
  118. _ url: URLConvertible,
  119. method: HTTPMethod = .get,
  120. parameters: Parameters? = nil,
  121. encoding: ParameterEncoding = URLEncoding.default,
  122. headers: HTTPHeaders? = nil)
  123. -> DataRequest
  124. {
  125. return SessionManager.default.request(
  126. url,
  127. method: method,
  128. parameters: parameters,
  129. encoding: encoding,
  130. headers: headers
  131. )
  132. }
  133. /// Creates a `DataRequest` using the default `SessionManager` to retrieve the contents of a URL based on the
  134. /// specified `urlRequest`.
  135. ///
  136. /// - parameter urlRequest: The URL request
  137. ///
  138. /// - returns: The created `DataRequest`.
  139. @discardableResult
  140. public func request(_ urlRequest: URLRequestConvertible) -> DataRequest {
  141. return SessionManager.default.request(urlRequest)
  142. }
  143. // MARK: - Download Request
  144. // MARK: URL Request
  145. /// Creates a `DownloadRequest` using the default `SessionManager` to retrieve the contents of the specified `url`,
  146. /// `method`, `parameters`, `encoding`, `headers` and save them to the `destination`.
  147. ///
  148. /// If `destination` is not specified, the contents will remain in the temporary location determined by the
  149. /// underlying URL session.
  150. ///
  151. /// - parameter url: The URL.
  152. /// - parameter method: The HTTP method. `.get` by default.
  153. /// - parameter parameters: The parameters. `nil` by default.
  154. /// - parameter encoding: The parameter encoding. `URLEncoding.default` by default.
  155. /// - parameter headers: The HTTP headers. `nil` by default.
  156. /// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default.
  157. ///
  158. /// - returns: The created `DownloadRequest`.
  159. @discardableResult
  160. public func download(
  161. _ url: URLConvertible,
  162. method: HTTPMethod = .get,
  163. parameters: Parameters? = nil,
  164. encoding: ParameterEncoding = URLEncoding.default,
  165. headers: HTTPHeaders? = nil,
  166. to destination: DownloadRequest.DownloadFileDestination? = nil)
  167. -> DownloadRequest
  168. {
  169. return SessionManager.default.download(
  170. url,
  171. method: method,
  172. parameters: parameters,
  173. encoding: encoding,
  174. headers: headers,
  175. to: destination
  176. )
  177. }
  178. /// Creates a `DownloadRequest` using the default `SessionManager` to retrieve the contents of a URL based on the
  179. /// specified `urlRequest` and save them to the `destination`.
  180. ///
  181. /// If `destination` is not specified, the contents will remain in the temporary location determined by the
  182. /// underlying URL session.
  183. ///
  184. /// - parameter urlRequest: The URL request.
  185. /// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default.
  186. ///
  187. /// - returns: The created `DownloadRequest`.
  188. @discardableResult
  189. public func download(
  190. _ urlRequest: URLRequestConvertible,
  191. to destination: DownloadRequest.DownloadFileDestination? = nil)
  192. -> DownloadRequest
  193. {
  194. return SessionManager.default.download(urlRequest, to: destination)
  195. }
  196. // MARK: Resume Data
  197. /// Creates a `DownloadRequest` using the default `SessionManager` from the `resumeData` produced from a
  198. /// previous request cancellation to retrieve the contents of the original request and save them to the `destination`.
  199. ///
  200. /// If `destination` is not specified, the contents will remain in the temporary location determined by the
  201. /// underlying URL session.
  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.DownloadFileDestination? = 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 = SessionManager.multipartFormDataEncodingMemoryThreshold,
  338. to url: URLConvertible,
  339. method: HTTPMethod = .post,
  340. headers: HTTPHeaders? = nil,
  341. encodingCompletion: ((SessionManager.MultipartFormDataEncodingResult) -> Void)?)
  342. {
  343. return SessionManager.default.upload(
  344. multipartFormData: multipartFormData,
  345. usingThreshold: encodingMemoryThreshold,
  346. to: url,
  347. method: method,
  348. headers: headers,
  349. encodingCompletion: encodingCompletion
  350. )
  351. }
  352. /// Encodes `multipartFormData` using `encodingMemoryThreshold` and the default `SessionManager` and
  353. /// calls `encodingCompletion` with new `UploadRequest` using the `urlRequest`.
  354. ///
  355. /// It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative
  356. /// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most
  357. /// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to
  358. /// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory
  359. /// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be
  360. /// used for larger payloads such as video content.
  361. ///
  362. /// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory
  363. /// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`,
  364. /// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk
  365. /// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding
  366. /// technique was used.
  367. ///
  368. /// - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`.
  369. /// - parameter encodingMemoryThreshold: The encoding memory threshold in bytes.
  370. /// `multipartFormDataEncodingMemoryThreshold` by default.
  371. /// - parameter urlRequest: The URL request.
  372. /// - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete.
  373. public func upload(
  374. multipartFormData: @escaping (MultipartFormData) -> Void,
  375. usingThreshold encodingMemoryThreshold: UInt64 = SessionManager.multipartFormDataEncodingMemoryThreshold,
  376. with urlRequest: URLRequestConvertible,
  377. encodingCompletion: ((SessionManager.MultipartFormDataEncodingResult) -> Void)?)
  378. {
  379. return SessionManager.default.upload(
  380. multipartFormData: multipartFormData,
  381. usingThreshold: encodingMemoryThreshold,
  382. with: urlRequest,
  383. encodingCompletion: encodingCompletion
  384. )
  385. }
  386. #if !os(watchOS)
  387. // MARK: - Stream Request
  388. // MARK: Hostname and Port
  389. /// Creates a `StreamRequest` using the default `SessionManager` for bidirectional streaming with the `hostname`
  390. /// and `port`.
  391. ///
  392. /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
  393. ///
  394. /// - parameter hostName: The hostname of the server to connect to.
  395. /// - parameter port: The port of the server to connect to.
  396. ///
  397. /// - returns: The created `StreamRequest`.
  398. @discardableResult
  399. public func stream(withHostName hostName: String, port: Int) -> StreamRequest {
  400. return SessionManager.default.stream(withHostName: hostName, port: port)
  401. }
  402. // MARK: NetService
  403. /// Creates a `StreamRequest` using the default `SessionManager` for bidirectional streaming with the `netService`.
  404. ///
  405. /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
  406. ///
  407. /// - parameter netService: The net service used to identify the endpoint.
  408. ///
  409. /// - returns: The created `StreamRequest`.
  410. @discardableResult
  411. public func stream(with netService: NetService) -> StreamRequest {
  412. return SessionManager.default.stream(with: netService)
  413. }
  414. #endif