Alamofire.swift 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  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 `URLStringConvertible` protocol can be used to construct URL strings, which are then used to
  26. /// construct URL requests.
  27. public protocol URLStringConvertible {
  28. /// A URL string that conforms to RFC 2396.
  29. ///
  30. /// Methods accepting a `URLStringConvertible` type parameter parse it according to RFCs 1738 and 1808.
  31. ///
  32. /// See https://tools.ietf.org/html/rfc2396
  33. /// See https://tools.ietf.org/html/rfc1738
  34. /// See https://tools.ietf.org/html/rfc1808
  35. var urlString: String? { get }
  36. /// Returns a URL string that conforms to RFC 2396 or throws if an `Error` was encoutered.
  37. ///
  38. /// Methods accepting a `URLStringConvertible` type parameter parse it according to RFCs 1738 and 1808.
  39. ///
  40. /// - throws: An `Error` if underlying url string is `nil`.
  41. ///
  42. /// - returns: A URL string.
  43. func asURLString() throws -> String
  44. }
  45. extension URLStringConvertible {
  46. public var urlString: String? { return try? asURLString() }
  47. }
  48. extension String: URLStringConvertible {
  49. /// Returns a URL string that conforms to RFC 2396.
  50. public func asURLString() throws -> String { return self }
  51. }
  52. extension URL: URLStringConvertible {
  53. /// Returns a URL string that conforms to RFC 2396.
  54. public func asURLString() throws -> String { return absoluteString }
  55. /// Creates a URL with the specified URL string if possible, otherwise throws an `Error`.
  56. ///
  57. /// - parameter urlString: The URL string convertible to create the URL with.
  58. ///
  59. /// - throws: An `AFError.invalidURLString` if invalid.
  60. ///
  61. /// - returns: A URL if created successfully, otherwise throws an `AFError`.
  62. public init(urlString: URLStringConvertible) throws {
  63. let urlString = try urlString.asURLString()
  64. guard let url = URL(string: urlString) else { throw AFError.invalidURLString(urlString: urlString) }
  65. self = url
  66. }
  67. }
  68. extension URLComponents: URLStringConvertible {
  69. /// Returns a URL string that conforms to RFC 2396.
  70. public func asURLString() throws -> String {
  71. guard let urlString = url?.urlString else { throw AFError.invalidURLString(urlString: self) }
  72. return urlString
  73. }
  74. }
  75. // MARK: -
  76. /// Types adopting the `URLRequestConvertible` protocol can be used to construct URL requests.
  77. public protocol URLRequestConvertible {
  78. /// The URL request.
  79. var urlRequest: URLRequest? { get }
  80. /// Returns a URL request or throws if an `Error` was encountered.
  81. ///
  82. /// - throws: An `Error` if the underlying `URLRequest` is `nil`.
  83. ///
  84. /// - returns: A URL request.
  85. func asURLRequest() throws -> URLRequest
  86. }
  87. extension URLRequestConvertible {
  88. /// The URL request.
  89. public var urlRequest: URLRequest? { return try? asURLRequest() }
  90. }
  91. extension URLRequest: URLRequestConvertible {
  92. /// Returns a URL request or throws if an `Error` was encountered.
  93. public func asURLRequest() throws -> URLRequest { return self }
  94. }
  95. // MARK: -
  96. extension URLRequest {
  97. /// Creates an instance with the specified `method`, `urlString` and `headers`.
  98. ///
  99. /// - parameter urlString: The URL string.
  100. /// - parameter method: The HTTP method.
  101. /// - parameter headers: The HTTP headers. `nil` by default.
  102. ///
  103. /// - returns: The new `URLRequest` instance.
  104. public init(urlString: URLStringConvertible, method: HTTPMethod, headers: HTTPHeaders? = nil) throws {
  105. let url = try URL(urlString: urlString)
  106. self.init(url: url)
  107. httpMethod = method.rawValue
  108. if let headers = headers {
  109. for (headerField, headerValue) in headers {
  110. setValue(headerValue, forHTTPHeaderField: headerField)
  111. }
  112. }
  113. }
  114. func adapt(using adapter: RequestAdapter?) throws -> URLRequest {
  115. guard let adapter = adapter else { return self }
  116. return try adapter.adapt(self)
  117. }
  118. }
  119. // MARK: - Data Request
  120. /// Creates a `DataRequest` using the default `SessionManager` to retrieve the contents of a URL based on the
  121. /// specified `urlString`, `method`, `parameters`, `encoding` and `headers`.
  122. ///
  123. /// - parameter urlString: The URL string.
  124. /// - parameter method: The HTTP method. `.get` by default.
  125. /// - parameter parameters: The parameters. `nil` by default.
  126. /// - parameter encoding: The parameter encoding. `URLEncoding.default` by default.
  127. /// - parameter headers: The HTTP headers. `nil` by default.
  128. ///
  129. /// - returns: The created `DataRequest`.
  130. @discardableResult
  131. public func request(
  132. _ urlString: URLStringConvertible,
  133. method: HTTPMethod = .get,
  134. parameters: Parameters? = nil,
  135. encoding: ParameterEncoding = URLEncoding.default,
  136. headers: HTTPHeaders? = nil)
  137. -> DataRequest
  138. {
  139. return SessionManager.default.request(
  140. urlString,
  141. method: method,
  142. parameters: parameters,
  143. encoding: encoding,
  144. headers: headers
  145. )
  146. }
  147. /// Creates a `DataRequest` using the default `SessionManager` to retrieve the contents of a URL based on the
  148. /// specified `urlRequest`.
  149. ///
  150. /// - parameter urlRequest: The URL request
  151. ///
  152. /// - returns: The created `DataRequest`.
  153. @discardableResult
  154. public func request(resource urlRequest: URLRequestConvertible) -> DataRequest {
  155. return SessionManager.default.request(resource: urlRequest)
  156. }
  157. // MARK: - Download Request
  158. // MARK: URL Request
  159. /// Creates a `DownloadRequest` using the default `SessionManager` to retrieve the contents of a URL based on the
  160. /// specified `urlString`, `method`, `parameters`, `encoding`, `headers` and save them to the `destination`.
  161. ///
  162. /// If `destination` is not specified, the contents will remain in the temporary location determined by the
  163. /// underlying URL session.
  164. ///
  165. /// - parameter urlString: The URL string.
  166. /// - parameter method: The HTTP method. `.get` by default.
  167. /// - parameter parameters: The parameters. `nil` by default.
  168. /// - parameter encoding: The parameter encoding. `URLEncoding.default` by default.
  169. /// - parameter headers: The HTTP headers. `nil` by default.
  170. /// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default.
  171. ///
  172. /// - returns: The created `DownloadRequest`.
  173. @discardableResult
  174. public func download(
  175. _ urlString: URLStringConvertible,
  176. method: HTTPMethod = .get,
  177. parameters: Parameters? = nil,
  178. encoding: ParameterEncoding = URLEncoding.default,
  179. headers: HTTPHeaders? = nil,
  180. to destination: DownloadRequest.DownloadFileDestination? = nil)
  181. -> DownloadRequest
  182. {
  183. return SessionManager.default.download(
  184. urlString,
  185. method: method,
  186. parameters: parameters,
  187. encoding: encoding,
  188. headers: headers,
  189. to: destination
  190. )
  191. }
  192. /// Creates a `DownloadRequest` using the default `SessionManager` to retrieve the contents of a URL based on the
  193. /// specified `urlRequest` and save them to the `destination`.
  194. ///
  195. /// If `destination` is not specified, the contents will remain in the temporary location determined by the
  196. /// underlying URL session.
  197. ///
  198. /// - parameter urlRequest: The URL request.
  199. /// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default.
  200. ///
  201. /// - returns: The created `DownloadRequest`.
  202. @discardableResult
  203. public func download(
  204. resource urlRequest: URLRequestConvertible,
  205. to destination: DownloadRequest.DownloadFileDestination? = nil)
  206. -> DownloadRequest
  207. {
  208. return SessionManager.default.download(resource: urlRequest, to: destination)
  209. }
  210. // MARK: Resume Data
  211. /// Creates a `DownloadRequest` using the default `SessionManager` from the `resumeData` produced from a
  212. /// previous request cancellation to retrieve the contents of the original request and save them to the `destination`.
  213. ///
  214. /// If `destination` is not specified, the contents will remain in the temporary location determined by the
  215. /// underlying URL session.
  216. ///
  217. /// - parameter resumeData: The resume data. This is an opaque data blob produced by `URLSessionDownloadTask`
  218. /// when a task is cancelled. See `URLSession -downloadTask(withResumeData:)` for additional
  219. /// information.
  220. /// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default.
  221. ///
  222. /// - returns: The created `DownloadRequest`.
  223. @discardableResult
  224. public func download(
  225. resourceWithin resumeData: Data,
  226. to destination: DownloadRequest.DownloadFileDestination? = nil)
  227. -> DownloadRequest
  228. {
  229. return SessionManager.default.download(resourceWithin: resumeData, to: destination)
  230. }
  231. // MARK: - Upload Request
  232. // MARK: File
  233. /// Creates an `UploadRequest` using the default `SessionManager` from the specified `method`, `urlString`
  234. /// and `headers` for uploading the `file`.
  235. ///
  236. /// - parameter file: The file to upload.
  237. /// - parameter urlString: The URL string.
  238. /// - parameter method: The HTTP method. `.post` by default.
  239. /// - parameter headers: The HTTP headers. `nil` by default.
  240. ///
  241. /// - returns: The created `UploadRequest`.
  242. @discardableResult
  243. public func upload(
  244. _ fileURL: URL,
  245. to urlString: URLStringConvertible,
  246. method: HTTPMethod = .post,
  247. headers: HTTPHeaders? = nil)
  248. -> UploadRequest
  249. {
  250. return SessionManager.default.upload(fileURL, to: urlString, method: method, headers: headers)
  251. }
  252. /// Creates a `UploadRequest` using the default `SessionManager` from the specified `urlRequest` for
  253. /// uploading the `file`.
  254. ///
  255. /// - parameter file: The file to upload.
  256. /// - parameter urlRequest: The URL request.
  257. ///
  258. /// - returns: The created `UploadRequest`.
  259. @discardableResult
  260. public func upload(_ fileURL: URL, with urlRequest: URLRequestConvertible) -> UploadRequest {
  261. return SessionManager.default.upload(fileURL, with: urlRequest)
  262. }
  263. // MARK: Data
  264. /// Creates an `UploadRequest` using the default `SessionManager` from the specified `method`, `urlString`
  265. /// and `headers` for uploading the `data`.
  266. ///
  267. /// - parameter data: The data to upload.
  268. /// - parameter urlString: The URL string.
  269. /// - parameter method: The HTTP method. `.post` by default.
  270. /// - parameter headers: The HTTP headers. `nil` by default.
  271. ///
  272. /// - returns: The created `UploadRequest`.
  273. @discardableResult
  274. public func upload(
  275. _ data: Data,
  276. to urlString: URLStringConvertible,
  277. method: HTTPMethod = .post,
  278. headers: HTTPHeaders? = nil)
  279. -> UploadRequest
  280. {
  281. return SessionManager.default.upload(data, to: urlString, method: method, headers: headers)
  282. }
  283. /// Creates an `UploadRequest` using the default `SessionManager` from the specified `urlRequest` for
  284. /// uploading the `data`.
  285. ///
  286. /// - parameter data: The data to upload.
  287. /// - parameter urlRequest: The URL request.
  288. ///
  289. /// - returns: The created `UploadRequest`.
  290. @discardableResult
  291. public func upload(_ data: Data, with urlRequest: URLRequestConvertible) -> UploadRequest {
  292. return SessionManager.default.upload(data, with: urlRequest)
  293. }
  294. // MARK: InputStream
  295. /// Creates an `UploadRequest` using the default `SessionManager` from the specified `method`, `urlString`
  296. /// and `headers` for uploading the `stream`.
  297. ///
  298. /// - parameter stream: The stream to upload.
  299. /// - parameter urlString: The URL string.
  300. /// - parameter method: The HTTP method. `.post` by default.
  301. /// - parameter headers: The HTTP headers. `nil` by default.
  302. ///
  303. /// - returns: The created `UploadRequest`.
  304. @discardableResult
  305. public func upload(
  306. _ stream: InputStream,
  307. to urlString: URLStringConvertible,
  308. method: HTTPMethod = .post,
  309. headers: HTTPHeaders? = nil)
  310. -> UploadRequest
  311. {
  312. return SessionManager.default.upload(stream, to: urlString, method: method, headers: headers)
  313. }
  314. /// Creates an `UploadRequest` using the default `SessionManager` from the specified `urlRequest` for
  315. /// uploading the `stream`.
  316. ///
  317. /// - parameter urlRequest: The URL request.
  318. /// - parameter stream: The stream to upload.
  319. ///
  320. /// - returns: The created `UploadRequest`.
  321. @discardableResult
  322. public func upload(_ stream: InputStream, with urlRequest: URLRequestConvertible) -> UploadRequest {
  323. return SessionManager.default.upload(stream, with: urlRequest)
  324. }
  325. // MARK: MultipartFormData
  326. /// Encodes `multipartFormData` using `encodingMemoryThreshold` with the default `SessionManager` and calls
  327. /// `encodingCompletion` with new `UploadRequest` using the `method`, `urlString` and `headers`.
  328. ///
  329. /// It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative
  330. /// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most
  331. /// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to
  332. /// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory
  333. /// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be
  334. /// used for larger payloads such as video content.
  335. ///
  336. /// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory
  337. /// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`,
  338. /// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk
  339. /// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding
  340. /// technique was used.
  341. ///
  342. /// - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`.
  343. /// - parameter encodingMemoryThreshold: The encoding memory threshold in bytes.
  344. /// `multipartFormDataEncodingMemoryThreshold` by default.
  345. /// - parameter urlString: The URL string.
  346. /// - parameter method: The HTTP method. `.post` by default.
  347. /// - parameter headers: The HTTP headers. `nil` by default.
  348. /// - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete.
  349. public func upload(
  350. multipartFormData: @escaping (MultipartFormData) -> Void,
  351. usingThreshold encodingMemoryThreshold: UInt64 = SessionManager.multipartFormDataEncodingMemoryThreshold,
  352. to urlString: URLStringConvertible,
  353. method: HTTPMethod = .post,
  354. headers: HTTPHeaders? = nil,
  355. encodingCompletion: ((SessionManager.MultipartFormDataEncodingResult) -> Void)?)
  356. {
  357. return SessionManager.default.upload(
  358. multipartFormData: multipartFormData,
  359. usingThreshold: encodingMemoryThreshold,
  360. to: urlString,
  361. method: method,
  362. headers: headers,
  363. encodingCompletion: encodingCompletion
  364. )
  365. }
  366. /// Encodes `multipartFormData` using `encodingMemoryThreshold` and the default `SessionManager` and
  367. /// calls `encodingCompletion` with new `UploadRequest` using the `urlRequest`.
  368. ///
  369. /// It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative
  370. /// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most
  371. /// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to
  372. /// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory
  373. /// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be
  374. /// used for larger payloads such as video content.
  375. ///
  376. /// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory
  377. /// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`,
  378. /// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk
  379. /// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding
  380. /// technique was used.
  381. ///
  382. /// - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`.
  383. /// - parameter encodingMemoryThreshold: The encoding memory threshold in bytes.
  384. /// `multipartFormDataEncodingMemoryThreshold` by default.
  385. /// - parameter urlRequest: The URL request.
  386. /// - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete.
  387. public func upload(
  388. multipartFormData: @escaping (MultipartFormData) -> Void,
  389. usingThreshold encodingMemoryThreshold: UInt64 = SessionManager.multipartFormDataEncodingMemoryThreshold,
  390. with urlRequest: URLRequestConvertible,
  391. encodingCompletion: ((SessionManager.MultipartFormDataEncodingResult) -> Void)?)
  392. {
  393. return SessionManager.default.upload(
  394. multipartFormData: multipartFormData,
  395. usingThreshold: encodingMemoryThreshold,
  396. with: urlRequest,
  397. encodingCompletion: encodingCompletion
  398. )
  399. }
  400. #if !os(watchOS)
  401. // MARK: - Stream Request
  402. // MARK: Hostname and Port
  403. /// Creates a `StreamRequest` using the default `SessionManager` for bidirectional streaming with the `hostname`
  404. /// and `port`.
  405. ///
  406. /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
  407. ///
  408. /// - parameter hostName: The hostname of the server to connect to.
  409. /// - parameter port: The port of the server to connect to.
  410. ///
  411. /// - returns: The created `StreamRequest`.
  412. @discardableResult
  413. public func stream(withHostName hostName: String, port: Int) -> StreamRequest {
  414. return SessionManager.default.stream(withHostName: hostName, port: port)
  415. }
  416. // MARK: NetService
  417. /// Creates a `StreamRequest` using the default `SessionManager` for bidirectional streaming with the `netService`.
  418. ///
  419. /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
  420. ///
  421. /// - parameter netService: The net service used to identify the endpoint.
  422. ///
  423. /// - returns: The created `StreamRequest`.
  424. @discardableResult
  425. public func stream(with netService: NetService) -> StreamRequest {
  426. return SessionManager.default.stream(with: netService)
  427. }
  428. #endif