Alamofire.swift 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649
  1. // Alamofire.swift
  2. //
  3. // Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. import Foundation
  23. /// Alamofire errors
  24. public let AlamofireErrorDomain = "com.alamofire.error"
  25. // MARK: - URLStringConvertible
  26. /**
  27. Types adopting the `URLStringConvertible` protocol can be used to construct URL strings, which are then used to construct URL requests.
  28. */
  29. public protocol URLStringConvertible {
  30. /**
  31. A URL that conforms to RFC 2396.
  32. Methods accepting a `URLStringConvertible` type parameter parse it according to RFCs 1738 and 1808.
  33. See http://tools.ietf.org/html/rfc2396
  34. See http://tools.ietf.org/html/rfc1738
  35. See http://tools.ietf.org/html/rfc1808
  36. */
  37. var URLString: String { get }
  38. }
  39. extension String: URLStringConvertible {
  40. public var URLString: String {
  41. return self
  42. }
  43. }
  44. extension NSURL: URLStringConvertible {
  45. public var URLString: String {
  46. return absoluteString!
  47. }
  48. }
  49. extension NSURLComponents: URLStringConvertible {
  50. public var URLString: String {
  51. return URL!.URLString
  52. }
  53. }
  54. extension NSURLRequest: URLStringConvertible {
  55. public var URLString: String {
  56. return URL!.URLString
  57. }
  58. }
  59. // MARK: - URLRequestConvertible
  60. /**
  61. Types adopting the `URLRequestConvertible` protocol can be used to construct URL requests.
  62. */
  63. public protocol URLRequestConvertible {
  64. /// The URL request.
  65. var URLRequest: NSURLRequest { get }
  66. }
  67. extension NSURLRequest: URLRequestConvertible {
  68. public var URLRequest: NSURLRequest {
  69. return self
  70. }
  71. }
  72. // MARK: - Validation
  73. extension Request {
  74. /**
  75. A closure used to validate a request that takes a URL request and URL response, and returns whether the request was valid.
  76. */
  77. public typealias Validation = (NSURLRequest, NSHTTPURLResponse) -> (Bool)
  78. /**
  79. Validates the request, using the specified closure.
  80. If validation fails, subsequent calls to response handlers will have an associated error.
  81. :param: validation A closure to validate the request.
  82. :returns: The request.
  83. */
  84. public func validate(validation: Validation) -> Self {
  85. delegate.queue.addOperationWithBlock {
  86. if self.response != nil && self.delegate.error == nil {
  87. if !validation(self.request, self.response!) {
  88. self.delegate.error = NSError(domain: AlamofireErrorDomain, code: -1, userInfo: nil)
  89. }
  90. }
  91. }
  92. return self
  93. }
  94. // MARK: Status Code
  95. /**
  96. Validates that the response has a status code in the specified range.
  97. If validation fails, subsequent calls to response handlers will have an associated error.
  98. :param: range The range of acceptable status codes.
  99. :returns: The request.
  100. */
  101. public func validate<S : SequenceType where S.Generator.Element == Int>(statusCode acceptableStatusCode: S) -> Self {
  102. return validate { (_, response) in
  103. return contains(acceptableStatusCode, response.statusCode)
  104. }
  105. }
  106. // MARK: Content-Type
  107. private struct MIMEType {
  108. let type: String
  109. let subtype: String
  110. init?(_ string: String) {
  111. let components = string.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).substringToIndex(string.rangeOfString(";")?.endIndex ?? string.endIndex).componentsSeparatedByString("/")
  112. if let type = components.first,
  113. subtype = components.last
  114. {
  115. self.type = type
  116. self.subtype = subtype
  117. } else {
  118. return nil
  119. }
  120. }
  121. func matches(MIME: MIMEType) -> Bool {
  122. switch (type, subtype) {
  123. case (MIME.type, MIME.subtype), (MIME.type, "*"), ("*", MIME.subtype), ("*", "*"):
  124. return true
  125. default:
  126. return false
  127. }
  128. }
  129. }
  130. /**
  131. Validates that the response has a content type in the specified array.
  132. If validation fails, subsequent calls to response handlers will have an associated error.
  133. :param: contentType The acceptable content types, which may specify wildcard types and/or subtypes.
  134. :returns: The request.
  135. */
  136. public func validate<S : SequenceType where S.Generator.Element == String>(contentType acceptableContentTypes: S) -> Self {
  137. return validate {(_, response) in
  138. if let responseContentType = response.MIMEType,
  139. responseMIMEType = MIMEType(responseContentType)
  140. {
  141. for contentType in acceptableContentTypes {
  142. if let acceptableMIMEType = MIMEType(contentType)
  143. where acceptableMIMEType.matches(responseMIMEType)
  144. {
  145. return true
  146. }
  147. }
  148. }
  149. return false
  150. }
  151. }
  152. // MARK: Automatic
  153. /**
  154. Validates that the response has a status code in the default acceptable range of 200...299, and that the content type matches any specified in the Accept HTTP header field.
  155. If validation fails, subsequent calls to response handlers will have an associated error.
  156. :returns: The request.
  157. */
  158. public func validate() -> Self {
  159. let acceptableStatusCodes: Range<Int> = 200..<300
  160. let acceptableContentTypes: [String] = {
  161. if let accept = self.request.valueForHTTPHeaderField("Accept") {
  162. return accept.componentsSeparatedByString(",")
  163. }
  164. return ["*/*"]
  165. }()
  166. return validate(statusCode: acceptableStatusCodes).validate(contentType: acceptableContentTypes)
  167. }
  168. }
  169. // MARK: - Upload
  170. extension Manager {
  171. private enum Uploadable {
  172. case Data(NSURLRequest, NSData)
  173. case File(NSURLRequest, NSURL)
  174. case Stream(NSURLRequest, NSInputStream)
  175. }
  176. private func upload(uploadable: Uploadable) -> Request {
  177. var uploadTask: NSURLSessionUploadTask!
  178. var HTTPBodyStream: NSInputStream?
  179. switch uploadable {
  180. case .Data(let request, let data):
  181. dispatch_sync(queue) {
  182. uploadTask = self.session.uploadTaskWithRequest(request, fromData: data)
  183. }
  184. case .File(let request, let fileURL):
  185. dispatch_sync(queue) {
  186. uploadTask = self.session.uploadTaskWithRequest(request, fromFile: fileURL)
  187. }
  188. case .Stream(let request, var stream):
  189. dispatch_sync(queue) {
  190. uploadTask = self.session.uploadTaskWithStreamedRequest(request)
  191. }
  192. HTTPBodyStream = stream
  193. }
  194. let request = Request(session: session, task: uploadTask)
  195. if HTTPBodyStream != nil {
  196. request.delegate.taskNeedNewBodyStream = { _, _ in
  197. return HTTPBodyStream
  198. }
  199. }
  200. delegate[request.delegate.task] = request.delegate
  201. if startRequestsImmediately {
  202. request.resume()
  203. }
  204. return request
  205. }
  206. // MARK: File
  207. /**
  208. Creates a request for uploading a file to the specified URL request.
  209. If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
  210. :param: URLRequest The URL request
  211. :param: file The file to upload
  212. :returns: The created upload request.
  213. */
  214. public func upload(URLRequest: URLRequestConvertible, file: NSURL) -> Request {
  215. return upload(.File(URLRequest.URLRequest, file))
  216. }
  217. /**
  218. Creates a request for uploading a file to the specified URL request.
  219. If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
  220. :param: method The HTTP method.
  221. :param: URLString The URL string.
  222. :param: file The file to upload
  223. :returns: The created upload request.
  224. */
  225. public func upload(method: Method, _ URLString: URLStringConvertible, file: NSURL) -> Request {
  226. return upload(URLRequest(method, URLString), file: file)
  227. }
  228. // MARK: Data
  229. /**
  230. Creates a request for uploading data to the specified URL request.
  231. If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
  232. :param: URLRequest The URL request
  233. :param: data The data to upload
  234. :returns: The created upload request.
  235. */
  236. public func upload(URLRequest: URLRequestConvertible, data: NSData) -> Request {
  237. return upload(.Data(URLRequest.URLRequest, data))
  238. }
  239. /**
  240. Creates a request for uploading data to the specified URL request.
  241. If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
  242. :param: method The HTTP method.
  243. :param: URLString The URL string.
  244. :param: data The data to upload
  245. :returns: The created upload request.
  246. */
  247. public func upload(method: Method, _ URLString: URLStringConvertible, data: NSData) -> Request {
  248. return upload(URLRequest(method, URLString), data: data)
  249. }
  250. // MARK: Stream
  251. /**
  252. Creates a request for uploading a stream to the specified URL request.
  253. If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
  254. :param: URLRequest The URL request
  255. :param: stream The stream to upload
  256. :returns: The created upload request.
  257. */
  258. public func upload(URLRequest: URLRequestConvertible, stream: NSInputStream) -> Request {
  259. return upload(.Stream(URLRequest.URLRequest, stream))
  260. }
  261. /**
  262. Creates a request for uploading a stream to the specified URL request.
  263. If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
  264. :param: method The HTTP method.
  265. :param: URLString The URL string.
  266. :param: stream The stream to upload.
  267. :returns: The created upload request.
  268. */
  269. public func upload(method: Method, _ URLString: URLStringConvertible, stream: NSInputStream) -> Request {
  270. return upload(URLRequest(method, URLString), stream: stream)
  271. }
  272. }
  273. extension Request {
  274. class UploadTaskDelegate: DataTaskDelegate {
  275. var uploadTask: NSURLSessionUploadTask! { return task as! NSURLSessionUploadTask }
  276. var uploadProgress: ((Int64, Int64, Int64) -> Void)!
  277. // MARK: NSURLSessionTaskDelegate
  278. func URLSession(session: NSURLSession!, task: NSURLSessionTask!, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
  279. progress.totalUnitCount = totalBytesExpectedToSend
  280. progress.completedUnitCount = totalBytesSent
  281. uploadProgress?(bytesSent, totalBytesSent, totalBytesExpectedToSend)
  282. }
  283. }
  284. }
  285. // MARK: - Response Serializers
  286. // MARK: String
  287. extension Request {
  288. /**
  289. Creates a response serializer that returns a string initialized from the response data with the specified string encoding.
  290. :param: encoding The string encoding. If `nil`, the string encoding will be determined from the server response, falling back to the default HTTP default character set, ISO-8859-1.
  291. :returns: A string response serializer.
  292. */
  293. public class func stringResponseSerializer(var encoding: NSStringEncoding? = nil) -> Serializer {
  294. return { (_, response, data) in
  295. if data == nil || data?.length == 0 {
  296. return (nil, nil)
  297. }
  298. if encoding == nil {
  299. if let encodingName = response?.textEncodingName {
  300. encoding = CFStringConvertEncodingToNSStringEncoding(CFStringConvertIANACharSetNameToEncoding(encodingName))
  301. }
  302. }
  303. let string = NSString(data: data!, encoding: encoding ?? NSISOLatin1StringEncoding)
  304. return (string, nil)
  305. }
  306. }
  307. /**
  308. Adds a handler to be called once the request has finished.
  309. :param: encoding The string encoding. If `nil`, the string encoding will be determined from the server response, falling back to the default HTTP default character set, ISO-8859-1.
  310. :param: completionHandler A closure to be executed once the request has finished. The closure takes 4 arguments: the URL request, the URL response, if one was received, the string, if one could be created from the URL response and data, and any error produced while creating the string.
  311. :returns: The request.
  312. */
  313. public func responseString(encoding: NSStringEncoding? = nil, completionHandler: (NSURLRequest, NSHTTPURLResponse?, String?, NSError?) -> Void) -> Self {
  314. return response(serializer: Request.stringResponseSerializer(encoding: encoding), completionHandler: { request, response, string, error in
  315. completionHandler(request, response, string as? String, error)
  316. })
  317. }
  318. }
  319. // MARK: JSON
  320. extension Request {
  321. /**
  322. Creates a response serializer that returns a JSON object constructed from the response data using `NSJSONSerialization` with the specified reading options.
  323. :param: options The JSON serialization reading options. `.AllowFragments` by default.
  324. :returns: A JSON object response serializer.
  325. */
  326. public class func JSONResponseSerializer(options: NSJSONReadingOptions = .AllowFragments) -> Serializer {
  327. return { (request, response, data) in
  328. if data == nil || data?.length == 0 {
  329. return (nil, nil)
  330. }
  331. var serializationError: NSError?
  332. let JSON: AnyObject? = NSJSONSerialization.JSONObjectWithData(data!, options: options, error: &serializationError)
  333. return (JSON, serializationError)
  334. }
  335. }
  336. /**
  337. Adds a handler to be called once the request has finished.
  338. :param: options The JSON serialization reading options. `.AllowFragments` by default.
  339. :param: completionHandler A closure to be executed once the request has finished. The closure takes 4 arguments: the URL request, the URL response, if one was received, the JSON object, if one could be created from the URL response and data, and any error produced while creating the JSON object.
  340. :returns: The request.
  341. */
  342. public func responseJSON(options: NSJSONReadingOptions = .AllowFragments, completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Self {
  343. return response(serializer: Request.JSONResponseSerializer(options: options), completionHandler: { (request, response, JSON, error) in
  344. completionHandler(request, response, JSON, error)
  345. })
  346. }
  347. }
  348. // MARK: Property List
  349. extension Request {
  350. /**
  351. Creates a response serializer that returns an object constructed from the response data using `NSPropertyListSerialization` with the specified reading options.
  352. :param: options The property list reading options. `0` by default.
  353. :returns: A property list object response serializer.
  354. */
  355. public class func propertyListResponseSerializer(options: NSPropertyListReadOptions = 0) -> Serializer {
  356. return { (request, response, data) in
  357. if data == nil || data?.length == 0 {
  358. return (nil, nil)
  359. }
  360. var propertyListSerializationError: NSError?
  361. let plist: AnyObject? = NSPropertyListSerialization.propertyListWithData(data!, options: options, format: nil, error: &propertyListSerializationError)
  362. return (plist, propertyListSerializationError)
  363. }
  364. }
  365. /**
  366. Adds a handler to be called once the request has finished.
  367. :param: options The property list reading options. `0` by default.
  368. :param: completionHandler A closure to be executed once the request has finished. The closure takes 4 arguments: the URL request, the URL response, if one was received, the property list, if one could be created from the URL response and data, and any error produced while creating the property list.
  369. :returns: The request.
  370. */
  371. public func responsePropertyList(options: NSPropertyListReadOptions = 0, completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Self {
  372. return response(serializer: Request.propertyListResponseSerializer(options: options), completionHandler: { (request, response, plist, error) in
  373. completionHandler(request, response, plist, error)
  374. })
  375. }
  376. }
  377. // MARK: - Convenience -
  378. func URLRequest(method: Method, URL: URLStringConvertible) -> NSURLRequest {
  379. let mutableURLRequest = NSMutableURLRequest(URL: NSURL(string: URL.URLString)!)
  380. mutableURLRequest.HTTPMethod = method.rawValue
  381. return mutableURLRequest
  382. }
  383. // MARK: - Request
  384. /**
  385. Creates a request using the shared manager instance for the specified method, URL string, parameters, and parameter encoding.
  386. :param: method The HTTP method.
  387. :param: URLString The URL string.
  388. :param: parameters The parameters. `nil` by default.
  389. :param: encoding The parameter encoding. `.URL` by default.
  390. :returns: The created request.
  391. */
  392. public func request(method: Method, URLString: URLStringConvertible, parameters: [String: AnyObject]? = nil, encoding: ParameterEncoding = .URL) -> Request {
  393. return Manager.sharedInstance.request(method, URLString, parameters: parameters, encoding: encoding)
  394. }
  395. /**
  396. Creates a request using the shared manager instance for the specified URL request.
  397. If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
  398. :param: URLRequest The URL request
  399. :returns: The created request.
  400. */
  401. public func request(URLRequest: URLRequestConvertible) -> Request {
  402. return Manager.sharedInstance.request(URLRequest.URLRequest)
  403. }
  404. // MARK: - Upload
  405. // MARK: File
  406. /**
  407. Creates an upload request using the shared manager instance for the specified method, URL string, and file.
  408. :param: method The HTTP method.
  409. :param: URLString The URL string.
  410. :param: file The file to upload.
  411. :returns: The created upload request.
  412. */
  413. public func upload(method: Method, URLString: URLStringConvertible, file: NSURL) -> Request {
  414. return Manager.sharedInstance.upload(method, URLString, file: file)
  415. }
  416. /**
  417. Creates an upload request using the shared manager instance for the specified URL request and file.
  418. :param: URLRequest The URL request.
  419. :param: file The file to upload.
  420. :returns: The created upload request.
  421. */
  422. public func upload(URLRequest: URLRequestConvertible, file: NSURL) -> Request {
  423. return Manager.sharedInstance.upload(URLRequest, file: file)
  424. }
  425. // MARK: Data
  426. /**
  427. Creates an upload request using the shared manager instance for the specified method, URL string, and data.
  428. :param: method The HTTP method.
  429. :param: URLString The URL string.
  430. :param: data The data to upload.
  431. :returns: The created upload request.
  432. */
  433. public func upload(method: Method, URLString: URLStringConvertible, data: NSData) -> Request {
  434. return Manager.sharedInstance.upload(method, URLString, data: data)
  435. }
  436. /**
  437. Creates an upload request using the shared manager instance for the specified URL request and data.
  438. :param: URLRequest The URL request.
  439. :param: data The data to upload.
  440. :returns: The created upload request.
  441. */
  442. public func upload(URLRequest: URLRequestConvertible, data: NSData) -> Request {
  443. return Manager.sharedInstance.upload(URLRequest, data: data)
  444. }
  445. // MARK: Stream
  446. /**
  447. Creates an upload request using the shared manager instance for the specified method, URL string, and stream.
  448. :param: method The HTTP method.
  449. :param: URLString The URL string.
  450. :param: stream The stream to upload.
  451. :returns: The created upload request.
  452. */
  453. public func upload(method: Method, URLString: URLStringConvertible, stream: NSInputStream) -> Request {
  454. return Manager.sharedInstance.upload(method, URLString, stream: stream)
  455. }
  456. /**
  457. Creates an upload request using the shared manager instance for the specified URL request and stream.
  458. :param: URLRequest The URL request.
  459. :param: stream The stream to upload.
  460. :returns: The created upload request.
  461. */
  462. public func upload(URLRequest: URLRequestConvertible, stream: NSInputStream) -> Request {
  463. return Manager.sharedInstance.upload(URLRequest, stream: stream)
  464. }
  465. // MARK: - Download
  466. // MARK: URL Request
  467. /**
  468. Creates a download request using the shared manager instance for the specified method and URL string.
  469. :param: method The HTTP method.
  470. :param: URLString The URL string.
  471. :param: destination The closure used to determine the destination of the downloaded file.
  472. :returns: The created download request.
  473. */
  474. public func download(method: Method, URLString: URLStringConvertible, destination: Request.DownloadFileDestination) -> Request {
  475. return Manager.sharedInstance.download(method, URLString, destination: destination)
  476. }
  477. /**
  478. Creates a download request using the shared manager instance for the specified URL request.
  479. :param: URLRequest The URL request.
  480. :param: destination The closure used to determine the destination of the downloaded file.
  481. :returns: The created download request.
  482. */
  483. public func download(URLRequest: URLRequestConvertible, destination: Request.DownloadFileDestination) -> Request {
  484. return Manager.sharedInstance.download(URLRequest, destination: destination)
  485. }
  486. // MARK: Resume Data
  487. /**
  488. Creates a request using the shared manager instance for downloading from the resume data produced from a previous request cancellation.
  489. :param: resumeData The resume data. This is an opaque data blob produced by `NSURLSessionDownloadTask` when a task is cancelled. See `NSURLSession -downloadTaskWithResumeData:` for additional information.
  490. :param: destination The closure used to determine the destination of the downloaded file.
  491. :returns: The created download request.
  492. */
  493. public func download(resumeData data: NSData, destination: Request.DownloadFileDestination) -> Request {
  494. return Manager.sharedInstance.download(data, destination: destination)
  495. }