Alamofire.swift 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023
  1. // Alamofire.swift
  2. //
  3. // Copyright (c) 2014 Alamofire (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. // HTTP Method Definitions; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
  24. public enum Method: String {
  25. case OPTIONS = "OPTIONS"
  26. case GET = "GET"
  27. case HEAD = "HEAD"
  28. case POST = "POST"
  29. case PUT = "PUT"
  30. case PATCH = "PATCH"
  31. case DELETE = "DELETE"
  32. case TRACE = "TRACE"
  33. case CONNECT = "CONNECT"
  34. }
  35. public enum ParameterEncoding {
  36. case URL
  37. case JSON//(NSJSONWritingOptions)
  38. case PropertyList(NSPropertyListFormat, NSPropertyListWriteOptions)
  39. case Custom((NSURLRequest, [String: AnyObject]?) -> (NSURLRequest, NSError?))
  40. public func encode(request: NSURLRequest, parameters: [String: AnyObject]?) -> (NSURLRequest, NSError?) {
  41. if parameters == nil {
  42. return (request, nil)
  43. }
  44. var mutableRequest: NSMutableURLRequest! = request.mutableCopy() as NSMutableURLRequest
  45. var error: NSError? = nil
  46. switch self {
  47. case .URL:
  48. func query(parameters: [String: AnyObject]) -> String {
  49. var components: [(String, String)] = []
  50. for key in sorted(Array(parameters.keys), <) {
  51. let value: AnyObject! = parameters[key]
  52. components += queryComponents(key, value)
  53. }
  54. return join("&", components.map{"\($0)=\($1)"} as [String])
  55. }
  56. func encodesParametersInURL(method: Method) -> Bool {
  57. switch method {
  58. case .GET, .HEAD, .DELETE:
  59. return true
  60. default:
  61. return false
  62. }
  63. }
  64. if encodesParametersInURL(Method.fromRaw(request.HTTPMethod!)!) {
  65. let URLComponents = NSURLComponents(URL: mutableRequest.URL!, resolvingAgainstBaseURL: false)
  66. URLComponents.query = (URLComponents.query != nil ? URLComponents.query! + "&" : "") + query(parameters!)
  67. mutableRequest.URL = URLComponents.URL
  68. } else {
  69. if mutableRequest.valueForHTTPHeaderField("Content-Type") == nil {
  70. mutableRequest.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
  71. }
  72. mutableRequest.HTTPBody = query(parameters!).dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
  73. }
  74. case .JSON://(let options):
  75. let options = NSJSONWritingOptions.allZeros
  76. if let data = NSJSONSerialization.dataWithJSONObject(parameters!, options: options, error: &error) {
  77. mutableRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
  78. mutableRequest.HTTPBody = data
  79. }
  80. case .PropertyList(let (format, options)):
  81. if let data = NSPropertyListSerialization.dataWithPropertyList(parameters!, format: format, options: options, error: &error) {
  82. mutableRequest.setValue("application/x-plist", forHTTPHeaderField: "Content-Type")
  83. mutableRequest.HTTPBody = data
  84. }
  85. case .Custom(let closure):
  86. return closure(request, parameters)
  87. }
  88. return (mutableRequest, error)
  89. }
  90. private func queryComponents(key: String, _ value: AnyObject) -> [(String, String)] {
  91. var components: [(String, String)] = []
  92. if let dictionary = value as? [String: AnyObject] {
  93. for (nestedKey, value) in dictionary {
  94. components += queryComponents("\(key)[\(nestedKey)]", value)
  95. }
  96. } else if let array = value as? [AnyObject] {
  97. for value in array {
  98. components += queryComponents("\(key)[]", value)
  99. }
  100. } else {
  101. components.extend([(key, "\(value)")])
  102. }
  103. return components
  104. }
  105. }
  106. // MARK: - URLStringConvertible
  107. public protocol URLStringConvertible {
  108. var URLString: String { get }
  109. }
  110. extension String: URLStringConvertible {
  111. public var URLString: String {
  112. return self
  113. }
  114. }
  115. extension NSURL: URLStringConvertible {
  116. public var URLString: String {
  117. return self.absoluteString!
  118. }
  119. }
  120. extension NSURLComponents: URLStringConvertible {
  121. public var URLString: String {
  122. return self.URL!.URLString
  123. }
  124. }
  125. extension NSURLRequest: URLStringConvertible {
  126. public var URLString: String {
  127. return self.URL.URLString
  128. }
  129. }
  130. // MARK: - URLRequestConvertible
  131. public protocol URLRequestConvertible {
  132. var URLRequest: NSURLRequest { get }
  133. }
  134. extension NSURLRequest: URLRequestConvertible {
  135. public var URLRequest: NSURLRequest {
  136. return self
  137. }
  138. }
  139. // MARK: -
  140. public class Manager {
  141. public class var sharedInstance: Manager {
  142. struct Singleton {
  143. static var configuration: NSURLSessionConfiguration = {
  144. var configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
  145. configuration.HTTPAdditionalHeaders = {
  146. // Accept-Encoding HTTP Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.3
  147. let acceptEncoding: String = "gzip;q=1.0,compress;q=0.5"
  148. // Accept-Language HTTP Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4
  149. let acceptLanguage: String = {
  150. var components: [String] = []
  151. for (index, languageCode) in enumerate(NSLocale.preferredLanguages() as [String]) {
  152. let q = 1.0 - (Double(index) * 0.1)
  153. components.append("\(languageCode);q=\(q)")
  154. if q <= 0.5 {
  155. break
  156. }
  157. }
  158. return join(",", components)
  159. }()
  160. // User-Agent Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.43
  161. let userAgent: String = {
  162. let info = NSBundle.mainBundle().infoDictionary
  163. let executable: AnyObject = info[kCFBundleExecutableKey] ?? "Unknown"
  164. let bundle: AnyObject = info[kCFBundleIdentifierKey] ?? "Unknown"
  165. let version: AnyObject = info[kCFBundleVersionKey] ?? "Unknown"
  166. let os: AnyObject = NSProcessInfo.processInfo().operatingSystemVersionString ?? "Unknown"
  167. var mutableUserAgent = NSMutableString(string: "\(executable)/\(bundle) (\(version); OS \(os))") as CFMutableString
  168. let transform = NSString(string: "Any-Latin; Latin-ASCII; [:^ASCII:] Remove") as CFString
  169. if CFStringTransform(mutableUserAgent, nil, transform, 0) == 1 {
  170. return mutableUserAgent as NSString
  171. }
  172. return "Alamofire"
  173. }()
  174. return ["Accept-Encoding": acceptEncoding,
  175. "Accept-Language": acceptLanguage,
  176. "User-Agent": userAgent]
  177. }()
  178. return configuration
  179. }()
  180. static let instance = Manager(configuration: configuration)
  181. }
  182. return Singleton.instance
  183. }
  184. let delegate: SessionDelegate
  185. let session: NSURLSession!
  186. let operationQueue: NSOperationQueue = NSOperationQueue()
  187. var automaticallyStartsRequests: Bool = true
  188. required public init(configuration: NSURLSessionConfiguration? = nil) {
  189. self.delegate = SessionDelegate()
  190. self.session = NSURLSession(configuration: configuration, delegate: self.delegate, delegateQueue: self.operationQueue)
  191. }
  192. deinit {
  193. self.session.invalidateAndCancel()
  194. }
  195. // MARK: -
  196. public func request(URLRequest: URLRequestConvertible) -> Request {
  197. var dataTask: NSURLSessionDataTask?
  198. dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
  199. dataTask = self.session.dataTaskWithRequest(URLRequest.URLRequest)
  200. }
  201. let request = Request(session: self.session, task: dataTask!)
  202. self.delegate[request.delegate.task] = request.delegate
  203. request.resume()
  204. return request
  205. }
  206. class SessionDelegate: NSObject, NSURLSessionDelegate, NSURLSessionTaskDelegate, NSURLSessionDataDelegate, NSURLSessionDownloadDelegate {
  207. private var subdelegates: [Int: Request.TaskDelegate]
  208. private subscript(task: NSURLSessionTask) -> Request.TaskDelegate? {
  209. get {
  210. return self.subdelegates[task.taskIdentifier]
  211. }
  212. set {
  213. self.subdelegates[task.taskIdentifier] = newValue
  214. }
  215. }
  216. var sessionDidBecomeInvalidWithError: ((NSURLSession!, NSError!) -> Void)?
  217. var sessionDidFinishEventsForBackgroundURLSession: ((NSURLSession!) -> Void)?
  218. var sessionDidReceiveChallenge: ((NSURLSession!, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential!))?
  219. var taskWillPerformHTTPRedirection: ((NSURLSession!, NSURLSessionTask!, NSHTTPURLResponse!, NSURLRequest!) -> (NSURLRequest!))?
  220. var taskDidReceiveChallenge: ((NSURLSession!, NSURLSessionTask!, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))?
  221. var taskDidSendBodyData: ((NSURLSession!, NSURLSessionTask!, Int64, Int64, Int64) -> Void)?
  222. var taskNeedNewBodyStream: ((NSURLSession!, NSURLSessionTask!) -> (NSInputStream!))?
  223. var dataTaskDidReceiveResponse: ((NSURLSession!, NSURLSessionDataTask!, NSURLResponse!) -> (NSURLSessionResponseDisposition))?
  224. var dataTaskDidBecomeDownloadTask: ((NSURLSession!, NSURLSessionDataTask!) -> Void)?
  225. var dataTaskDidReceiveData: ((NSURLSession!, NSURLSessionDataTask!, NSData!) -> Void)?
  226. var dataTaskWillCacheResponse: ((NSURLSession!, NSURLSessionDataTask!, NSCachedURLResponse!) -> (NSCachedURLResponse))?
  227. var downloadTaskDidFinishDownloadingToURL: ((NSURLSession!, NSURLSessionDownloadTask!, NSURL) -> (NSURL))?
  228. var downloadTaskDidWriteData: ((NSURLSession!, NSURLSessionDownloadTask!, Int64, Int64, Int64) -> Void)?
  229. var downloadTaskDidResumeAtOffset: ((NSURLSession!, NSURLSessionDownloadTask!, Int64, Int64) -> Void)?
  230. required override init() {
  231. self.subdelegates = Dictionary()
  232. super.init()
  233. }
  234. // MARK: NSURLSessionDelegate
  235. func URLSession(session: NSURLSession!, didBecomeInvalidWithError error: NSError!) {
  236. self.sessionDidBecomeInvalidWithError?(session, error)
  237. }
  238. func URLSession(session: NSURLSession!, didReceiveChallenge challenge: NSURLAuthenticationChallenge!, completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential!) -> Void)!) {
  239. if self.sessionDidReceiveChallenge != nil {
  240. completionHandler(self.sessionDidReceiveChallenge!(session, challenge))
  241. } else {
  242. completionHandler(.PerformDefaultHandling, nil)
  243. }
  244. }
  245. func URLSessionDidFinishEventsForBackgroundURLSession(session: NSURLSession!) {
  246. self.sessionDidFinishEventsForBackgroundURLSession?(session)
  247. }
  248. // MARK: NSURLSessionTaskDelegate
  249. func URLSession(session: NSURLSession!, task: NSURLSessionTask!, willPerformHTTPRedirection response: NSHTTPURLResponse!, newRequest request: NSURLRequest!, completionHandler: ((NSURLRequest!) -> Void)!) {
  250. var redirectRequest = request
  251. if self.taskWillPerformHTTPRedirection != nil {
  252. redirectRequest = self.taskWillPerformHTTPRedirection!(session, task, response, request)
  253. }
  254. completionHandler(redirectRequest)
  255. }
  256. func URLSession(session: NSURLSession!, task: NSURLSessionTask!, didReceiveChallenge challenge: NSURLAuthenticationChallenge!, completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential!) -> Void)!) {
  257. if let delegate = self[task] {
  258. delegate.URLSession(session, task: task, didReceiveChallenge: challenge, completionHandler: completionHandler)
  259. } else {
  260. self.URLSession(session, didReceiveChallenge: challenge, completionHandler: completionHandler)
  261. }
  262. }
  263. func URLSession(session: NSURLSession!, task: NSURLSessionTask!, needNewBodyStream completionHandler: ((NSInputStream!) -> Void)!) {
  264. if let delegate = self[task] {
  265. delegate.URLSession(session, task: task, needNewBodyStream: completionHandler)
  266. }
  267. }
  268. func URLSession(session: NSURLSession!, task: NSURLSessionTask!, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
  269. if let delegate = self[task] as? Request.UploadTaskDelegate {
  270. delegate.URLSession(session, task: task, didSendBodyData: bytesSent, totalBytesSent: totalBytesSent, totalBytesExpectedToSend: totalBytesExpectedToSend)
  271. }
  272. }
  273. func URLSession(session: NSURLSession!, task: NSURLSessionTask!, didCompleteWithError error: NSError!) {
  274. if let delegate = self[task] {
  275. delegate.URLSession(session, task: task, didCompleteWithError: error)
  276. self[task] = nil
  277. }
  278. }
  279. // MARK: NSURLSessionDataDelegate
  280. func URLSession(session: NSURLSession!, dataTask: NSURLSessionDataTask!, didReceiveResponse response: NSURLResponse!, completionHandler: ((NSURLSessionResponseDisposition) -> Void)!) {
  281. var disposition: NSURLSessionResponseDisposition = .Allow
  282. if self.dataTaskDidReceiveResponse != nil {
  283. disposition = self.dataTaskDidReceiveResponse!(session, dataTask, response)
  284. }
  285. completionHandler(disposition)
  286. }
  287. func URLSession(session: NSURLSession!, dataTask: NSURLSessionDataTask!, didBecomeDownloadTask downloadTask: NSURLSessionDownloadTask!) {
  288. let downloadDelegate = Request.DownloadTaskDelegate(task: downloadTask)
  289. self[downloadTask] = downloadDelegate
  290. }
  291. func URLSession(session: NSURLSession!, dataTask: NSURLSessionDataTask!, didReceiveData data: NSData!) {
  292. if let delegate = self[dataTask] as? Request.DataTaskDelegate {
  293. delegate.URLSession(session, dataTask: dataTask, didReceiveData: data)
  294. }
  295. self.dataTaskDidReceiveData?(session, dataTask, data)
  296. }
  297. func URLSession(session: NSURLSession!, dataTask: NSURLSessionDataTask!, willCacheResponse proposedResponse: NSCachedURLResponse!, completionHandler: ((NSCachedURLResponse!) -> Void)!) {
  298. var cachedResponse = proposedResponse
  299. if self.dataTaskWillCacheResponse != nil {
  300. cachedResponse = self.dataTaskWillCacheResponse!(session, dataTask, proposedResponse)
  301. }
  302. completionHandler(cachedResponse)
  303. }
  304. // MARK: NSURLSessionDownloadDelegate
  305. func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL) {
  306. if let delegate = self[downloadTask] as? Request.DownloadTaskDelegate {
  307. delegate.URLSession(session, downloadTask: downloadTask, didFinishDownloadingToURL: location)
  308. }
  309. self.downloadTaskDidFinishDownloadingToURL?(session, downloadTask, location)
  310. }
  311. func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
  312. if let delegate = self[downloadTask] as? Request.DownloadTaskDelegate {
  313. delegate.URLSession(session, downloadTask: downloadTask, didWriteData: bytesWritten, totalBytesWritten: totalBytesWritten, totalBytesExpectedToWrite: totalBytesExpectedToWrite)
  314. }
  315. self.downloadTaskDidWriteData?(session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite)
  316. }
  317. func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64) {
  318. if let delegate = self[downloadTask] as? Request.DownloadTaskDelegate {
  319. delegate.URLSession(session, downloadTask: downloadTask, didResumeAtOffset: fileOffset, expectedTotalBytes: expectedTotalBytes)
  320. }
  321. self.downloadTaskDidResumeAtOffset?(session, downloadTask, fileOffset, expectedTotalBytes)
  322. }
  323. // MARK: NSObject
  324. override func respondsToSelector(selector: Selector) -> Bool {
  325. switch selector {
  326. case "URLSession:didBecomeInvalidWithError:":
  327. return (self.sessionDidBecomeInvalidWithError != nil)
  328. case "URLSession:didReceiveChallenge:completionHandler:":
  329. return (self.sessionDidReceiveChallenge != nil)
  330. case "URLSessionDidFinishEventsForBackgroundURLSession:":
  331. return (self.sessionDidFinishEventsForBackgroundURLSession != nil)
  332. case "URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:":
  333. return (self.taskWillPerformHTTPRedirection != nil)
  334. case "URLSession:dataTask:didReceiveResponse:completionHandler:":
  335. return (self.dataTaskDidReceiveResponse != nil)
  336. case "URLSession:dataTask:willCacheResponse:completionHandler:":
  337. return (self.dataTaskWillCacheResponse != nil)
  338. default:
  339. return self.dynamicType.instancesRespondToSelector(selector)
  340. }
  341. }
  342. }
  343. }
  344. // MARK: -
  345. public class Request {
  346. private let delegate: TaskDelegate
  347. private var session: NSURLSession
  348. private var task: NSURLSessionTask { return self.delegate.task }
  349. public var request: NSURLRequest { return self.task.originalRequest }
  350. public var response: NSHTTPURLResponse? { return self.task.response as? NSHTTPURLResponse }
  351. public var progress: NSProgress? { return self.delegate.progress }
  352. private init(session: NSURLSession, task: NSURLSessionTask) {
  353. self.session = session
  354. switch task {
  355. case is NSURLSessionUploadTask:
  356. self.delegate = UploadTaskDelegate(task: task)
  357. case is NSURLSessionDataTask:
  358. self.delegate = DataTaskDelegate(task: task)
  359. case is NSURLSessionDownloadTask:
  360. self.delegate = DownloadTaskDelegate(task: task)
  361. default:
  362. self.delegate = TaskDelegate(task: task)
  363. }
  364. }
  365. // MARK: Authentication
  366. public func authenticate(HTTPBasic user: String, password: String) -> Self {
  367. let credential = NSURLCredential(user: user, password: password, persistence: .ForSession)
  368. let protectionSpace = NSURLProtectionSpace(host: self.request.URL.host!, port: 0, `protocol`: self.request.URL.scheme, realm: nil, authenticationMethod: NSURLAuthenticationMethodHTTPBasic)
  369. return authenticate(usingCredential: credential, forProtectionSpace: protectionSpace)
  370. }
  371. public func authenticate(usingCredential credential: NSURLCredential, forProtectionSpace protectionSpace: NSURLProtectionSpace) -> Self {
  372. self.session.configuration.URLCredentialStorage?.setCredential(credential, forProtectionSpace: protectionSpace)
  373. return self
  374. }
  375. // MARK: Progress
  376. public func progress(closure: ((Int64, Int64, Int64) -> Void)? = nil) -> Self {
  377. if let uploadDelegate = self.delegate as? UploadTaskDelegate {
  378. uploadDelegate.uploadProgress = closure
  379. } else if let downloadDelegate = self.delegate as? DownloadTaskDelegate {
  380. downloadDelegate.downloadProgress = closure
  381. } else if let dataDelegate = self.delegate as? DataTaskDelegate {
  382. dataDelegate.dataProgress = closure
  383. }
  384. return self
  385. }
  386. // MARK: Response
  387. public typealias Serializer = (NSURLRequest, NSHTTPURLResponse?, NSData?) -> (AnyObject?, NSError?)
  388. public class func responseDataSerializer() -> Serializer {
  389. return { (request, response, data) in
  390. return (data, nil)
  391. }
  392. }
  393. public func response(completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Self {
  394. return response(Request.responseDataSerializer(), completionHandler: completionHandler)
  395. }
  396. public func response(priority: Int = DISPATCH_QUEUE_PRIORITY_DEFAULT, queue: dispatch_queue_t? = nil, serializer: Serializer, completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Self {
  397. dispatch_async(self.delegate.queue, {
  398. dispatch_async(dispatch_get_global_queue(priority, 0), {
  399. if var error = self.delegate.error {
  400. dispatch_async(queue ?? dispatch_get_main_queue(), {
  401. completionHandler(self.request, self.response, nil, error)
  402. })
  403. } else {
  404. let (responseObject: AnyObject?, serializationError: NSError?) = serializer(self.request, self.response, self.delegate.data)
  405. dispatch_async(queue ?? dispatch_get_main_queue(), {
  406. completionHandler(self.request, self.response, responseObject, serializationError)
  407. })
  408. }
  409. })
  410. })
  411. return self
  412. }
  413. public func suspend() {
  414. self.task.suspend()
  415. }
  416. public func resume() {
  417. self.task.resume()
  418. }
  419. public func cancel() {
  420. if let downloadDelegate = self.delegate as? DownloadTaskDelegate {
  421. downloadDelegate.downloadTask.cancelByProducingResumeData { (data) in
  422. downloadDelegate.resumeData = data
  423. }
  424. } else {
  425. self.task.cancel()
  426. }
  427. }
  428. private class TaskDelegate: NSObject, NSURLSessionTaskDelegate {
  429. let task: NSURLSessionTask
  430. let queue: dispatch_queue_t?
  431. let progress: NSProgress
  432. var data: NSData? { return nil }
  433. private(set) var error: NSError?
  434. var taskWillPerformHTTPRedirection: ((NSURLSession!, NSURLSessionTask!, NSHTTPURLResponse!, NSURLRequest!) -> (NSURLRequest!))?
  435. var taskDidReceiveChallenge: ((NSURLSession!, NSURLSessionTask!, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))?
  436. var taskDidSendBodyData: ((NSURLSession!, NSURLSessionTask!, Int64, Int64, Int64) -> Void)?
  437. var taskNeedNewBodyStream: ((NSURLSession!, NSURLSessionTask!) -> (NSInputStream!))?
  438. init(task: NSURLSessionTask) {
  439. self.task = task
  440. self.progress = NSProgress(totalUnitCount: 0)
  441. let label: String = "com.alamofire.task-\(task.taskIdentifier)"
  442. let queue = dispatch_queue_create((label as NSString).UTF8String, DISPATCH_QUEUE_SERIAL)
  443. dispatch_suspend(queue)
  444. self.queue = queue
  445. }
  446. // MARK: NSURLSessionTaskDelegate
  447. func URLSession(session: NSURLSession!, task: NSURLSessionTask!, willPerformHTTPRedirection response: NSHTTPURLResponse!, newRequest request: NSURLRequest!, completionHandler: ((NSURLRequest!) -> Void)!) {
  448. var redirectRequest = request
  449. if self.taskWillPerformHTTPRedirection != nil {
  450. redirectRequest = self.taskWillPerformHTTPRedirection!(session, task, response, request)
  451. }
  452. completionHandler(redirectRequest)
  453. }
  454. func URLSession(session: NSURLSession!, task: NSURLSessionTask!, didReceiveChallenge challenge: NSURLAuthenticationChallenge!, completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential!) -> Void)!) {
  455. var disposition: NSURLSessionAuthChallengeDisposition = .PerformDefaultHandling
  456. var credential: NSURLCredential?
  457. if self.taskDidReceiveChallenge != nil {
  458. (disposition, credential) = self.taskDidReceiveChallenge!(session, task, challenge)
  459. } else {
  460. if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
  461. // TODO: Incorporate Trust Evaluation & TLS Chain Validation
  462. credential = NSURLCredential(forTrust: challenge.protectionSpace.serverTrust)
  463. disposition = .UseCredential
  464. }
  465. }
  466. completionHandler(disposition, credential)
  467. }
  468. func URLSession(session: NSURLSession!, task: NSURLSessionTask!, needNewBodyStream completionHandler: ((NSInputStream!) -> Void)!) {
  469. var bodyStream: NSInputStream?
  470. if self.taskNeedNewBodyStream != nil {
  471. bodyStream = self.taskNeedNewBodyStream!(session, task)
  472. }
  473. completionHandler(bodyStream)
  474. }
  475. func URLSession(session: NSURLSession!, task: NSURLSessionTask!, didCompleteWithError error: NSError!) {
  476. self.error = error
  477. dispatch_resume(self.queue)
  478. }
  479. }
  480. private class DataTaskDelegate: TaskDelegate, NSURLSessionDataDelegate {
  481. var dataTask: NSURLSessionDataTask! { return self.task as NSURLSessionDataTask }
  482. private var mutableData: NSMutableData
  483. override var data: NSData? {
  484. return self.mutableData
  485. }
  486. private var expectedContentLength: Int64?
  487. var dataTaskDidReceiveResponse: ((NSURLSession!, NSURLSessionDataTask!, NSURLResponse!) -> (NSURLSessionResponseDisposition))?
  488. var dataTaskDidBecomeDownloadTask: ((NSURLSession!, NSURLSessionDataTask!) -> Void)?
  489. var dataTaskDidReceiveData: ((NSURLSession!, NSURLSessionDataTask!, NSData!) -> Void)?
  490. var dataTaskWillCacheResponse: ((NSURLSession!, NSURLSessionDataTask!, NSCachedURLResponse!) -> (NSCachedURLResponse))?
  491. var dataProgress: ((bytesReceived: Int64, totalBytesReceived: Int64, totalBytesExpectedToReceive: Int64) -> Void)?
  492. override init(task: NSURLSessionTask) {
  493. self.mutableData = NSMutableData()
  494. super.init(task: task)
  495. }
  496. // MARK: NSURLSessionDataDelegate
  497. func URLSession(session: NSURLSession!, dataTask: NSURLSessionDataTask!, didReceiveResponse response: NSURLResponse!, completionHandler: ((NSURLSessionResponseDisposition) -> Void)!) {
  498. var disposition: NSURLSessionResponseDisposition = .Allow
  499. expectedContentLength = response.expectedContentLength
  500. if self.dataTaskDidReceiveResponse != nil {
  501. disposition = self.dataTaskDidReceiveResponse!(session, dataTask, response)
  502. }
  503. completionHandler(disposition)
  504. }
  505. func URLSession(session: NSURLSession!, dataTask: NSURLSessionDataTask!, didBecomeDownloadTask downloadTask: NSURLSessionDownloadTask!) {
  506. self.dataTaskDidBecomeDownloadTask?(session, dataTask)
  507. }
  508. func URLSession(session: NSURLSession!, dataTask: NSURLSessionDataTask!, didReceiveData data: NSData!) {
  509. self.dataTaskDidReceiveData?(session, dataTask, data)
  510. self.mutableData.appendData(data)
  511. if let expectedContentLength = dataTask?.response?.expectedContentLength {
  512. self.dataProgress?(bytesReceived: Int64(data.length), totalBytesReceived: Int64(self.mutableData.length), totalBytesExpectedToReceive: expectedContentLength)
  513. }
  514. }
  515. func URLSession(session: NSURLSession!, dataTask: NSURLSessionDataTask!, willCacheResponse proposedResponse: NSCachedURLResponse!, completionHandler: ((NSCachedURLResponse!) -> Void)!) {
  516. var cachedResponse = proposedResponse
  517. if self.dataTaskWillCacheResponse != nil {
  518. cachedResponse = self.dataTaskWillCacheResponse!(session, dataTask, proposedResponse)
  519. }
  520. completionHandler(cachedResponse)
  521. }
  522. }
  523. }
  524. // MARK: - Upload
  525. extension Manager {
  526. private enum Uploadable {
  527. case Data(NSURLRequest, NSData)
  528. case File(NSURLRequest, NSURL)
  529. case Stream(NSURLRequest, NSInputStream)
  530. }
  531. private func upload(uploadable: Uploadable) -> Request {
  532. var uploadTask: NSURLSessionUploadTask!
  533. var stream: NSInputStream?
  534. switch uploadable {
  535. case .Data(let request, let data):
  536. uploadTask = self.session.uploadTaskWithRequest(request, fromData: data)
  537. case .File(let request, let fileURL):
  538. uploadTask = self.session.uploadTaskWithRequest(request, fromFile: fileURL)
  539. case .Stream(let request, var stream):
  540. uploadTask = self.session.uploadTaskWithStreamedRequest(request)
  541. }
  542. let request = Request(session: self.session, task: uploadTask)
  543. if stream != nil {
  544. request.delegate.taskNeedNewBodyStream = { _, _ in
  545. return stream
  546. }
  547. }
  548. self.delegate[request.delegate.task] = request.delegate
  549. if self.automaticallyStartsRequests {
  550. request.resume()
  551. }
  552. return request
  553. }
  554. // MARK: File
  555. func upload(request: NSURLRequest, file: NSURL) -> Request {
  556. return upload(.File(request, file))
  557. }
  558. // MARK: Data
  559. func upload(request: NSURLRequest, data: NSData) -> Request {
  560. return upload(.Data(request, data))
  561. }
  562. // MARK: Stream
  563. func upload(request: NSURLRequest, stream: NSInputStream) -> Request {
  564. return upload(.Stream(request, stream))
  565. }
  566. }
  567. extension Request {
  568. private class UploadTaskDelegate: DataTaskDelegate {
  569. var uploadTask: NSURLSessionUploadTask! { return self.task as NSURLSessionUploadTask }
  570. var uploadProgress: ((Int64, Int64, Int64) -> Void)!
  571. // MARK: NSURLSessionTaskDelegate
  572. func URLSession(session: NSURLSession!, task: NSURLSessionTask!, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
  573. if self.uploadProgress != nil {
  574. self.uploadProgress(bytesSent, totalBytesSent, totalBytesExpectedToSend)
  575. }
  576. self.progress.totalUnitCount = totalBytesExpectedToSend
  577. self.progress.completedUnitCount = totalBytesSent
  578. }
  579. }
  580. }
  581. // MARK: - Download
  582. extension Manager {
  583. private enum Downloadable {
  584. case Request(NSURLRequest)
  585. case ResumeData(NSData)
  586. }
  587. private func download(downloadable: Downloadable, destination: (NSURL, NSHTTPURLResponse) -> (NSURL)) -> Request {
  588. var downloadTask: NSURLSessionDownloadTask!
  589. switch downloadable {
  590. case .Request(let request):
  591. downloadTask = self.session.downloadTaskWithRequest(request)
  592. case .ResumeData(let resumeData):
  593. downloadTask = self.session.downloadTaskWithResumeData(resumeData)
  594. }
  595. let request = Request(session: self.session, task: downloadTask)
  596. if let downloadDelegate = request.delegate as? Request.DownloadTaskDelegate {
  597. downloadDelegate.downloadTaskDidFinishDownloadingToURL = { (session, downloadTask, URL) in
  598. return destination(URL, downloadTask.response as NSHTTPURLResponse)
  599. }
  600. }
  601. self.delegate[request.delegate.task] = request.delegate
  602. if self.automaticallyStartsRequests {
  603. request.resume()
  604. }
  605. return request
  606. }
  607. // MARK: Request
  608. public func download(request: NSURLRequest, destination: (NSURL, NSHTTPURLResponse) -> (NSURL)) -> Request {
  609. return download(.Request(request), destination: destination)
  610. }
  611. // MARK: Resume Data
  612. public func download(resumeData: NSData, destination: (NSURL, NSHTTPURLResponse) -> (NSURL)) -> Request {
  613. return download(.ResumeData(resumeData), destination: destination)
  614. }
  615. }
  616. extension Request {
  617. public class func suggestedDownloadDestination(directory: NSSearchPathDirectory = .DocumentDirectory, domain: NSSearchPathDomainMask = .UserDomainMask) -> (NSURL, NSHTTPURLResponse) -> (NSURL) {
  618. return { (temporaryURL, response) -> (NSURL) in
  619. if let directoryURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0] as? NSURL {
  620. return directoryURL.URLByAppendingPathComponent(response.suggestedFilename!)
  621. }
  622. return temporaryURL
  623. }
  624. }
  625. private class DownloadTaskDelegate: TaskDelegate, NSURLSessionDownloadDelegate {
  626. var downloadTask: NSURLSessionDownloadTask! { return self.task as NSURLSessionDownloadTask }
  627. var downloadProgress: ((Int64, Int64, Int64) -> Void)?
  628. var resumeData: NSData?
  629. override var data: NSData? { return self.resumeData }
  630. var downloadTaskDidFinishDownloadingToURL: ((NSURLSession!, NSURLSessionDownloadTask!, NSURL) -> (NSURL))?
  631. var downloadTaskDidWriteData: ((NSURLSession!, NSURLSessionDownloadTask!, Int64, Int64, Int64) -> Void)?
  632. var downloadTaskDidResumeAtOffset: ((NSURLSession!, NSURLSessionDownloadTask!, Int64, Int64) -> Void)?
  633. // MARK: NSURLSessionDownloadDelegate
  634. func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL) {
  635. if self.downloadTaskDidFinishDownloadingToURL != nil {
  636. let destination = self.downloadTaskDidFinishDownloadingToURL!(session, downloadTask, location)
  637. var fileManagerError: NSError?
  638. NSFileManager.defaultManager().moveItemAtURL(location, toURL: destination, error: &fileManagerError)
  639. // TODO: NSNotification on failure
  640. }
  641. }
  642. func URLSession(session: NSURLSession!, downloadTask: NSURLSessionDownloadTask!, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
  643. self.downloadTaskDidWriteData?(session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite)
  644. self.downloadProgress?(bytesWritten, totalBytesWritten, totalBytesExpectedToWrite)
  645. self.progress.totalUnitCount = totalBytesExpectedToWrite
  646. self.progress.completedUnitCount = totalBytesWritten
  647. }
  648. func URLSession(session: NSURLSession!, downloadTask: NSURLSessionDownloadTask!, didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64) {
  649. self.downloadTaskDidResumeAtOffset?(session, downloadTask, fileOffset, expectedTotalBytes)
  650. self.progress.totalUnitCount = expectedTotalBytes
  651. self.progress.completedUnitCount = fileOffset
  652. }
  653. }
  654. }
  655. // MARK: - Printable
  656. extension Request: Printable {
  657. public var description: String {
  658. var components: [String] = []
  659. if self.request.HTTPMethod != nil {
  660. components.append(self.request.HTTPMethod!)
  661. }
  662. components.append(self.request.URL.absoluteString!)
  663. if self.response != nil {
  664. components.append("\(self.response!.statusCode)")
  665. }
  666. return join(" ", components)
  667. }
  668. }
  669. extension Request: DebugPrintable {
  670. func cURLRepresentation() -> String {
  671. var components: [String] = ["$ curl -i"]
  672. let URL = self.request.URL
  673. if self.request.HTTPMethod != nil && self.request.HTTPMethod != "GET" {
  674. components.append("-X \(self.request.HTTPMethod!)")
  675. }
  676. if let credentialStorage = self.session.configuration.URLCredentialStorage {
  677. let protectionSpace = NSURLProtectionSpace(host: URL.host!, port: URL.port ?? 0, `protocol`: URL.scheme, realm: URL.host, authenticationMethod: NSURLAuthenticationMethodHTTPBasic)
  678. if let credentials = credentialStorage.credentialsForProtectionSpace(protectionSpace)?.values.array {
  679. if !credentials.isEmpty {
  680. if let credential = credentials[0] as? NSURLCredential {
  681. components.append("-u \(credential.user):\(credential.password)")
  682. }
  683. }
  684. }
  685. }
  686. if let cookieStorage = self.session.configuration.HTTPCookieStorage {
  687. if let cookies = cookieStorage.cookiesForURL(URL) as? [NSHTTPCookie] {
  688. if !cookies.isEmpty {
  689. let string = cookies.reduce(""){ $0 + "\($1.name)=\($1.value);" }
  690. components.append("-b \"\(string.substringToIndex(string.endIndex.predecessor()))\"")
  691. }
  692. }
  693. }
  694. for (field, value) in self.request.allHTTPHeaderFields! {
  695. switch field {
  696. case "Cookie":
  697. continue
  698. default:
  699. components.append("-H \"\(field): \(value)\"")
  700. }
  701. }
  702. if let HTTPBody = self.request.HTTPBody {
  703. components.append("-d \"\(NSString(data: HTTPBody, encoding: NSUTF8StringEncoding))\"")
  704. }
  705. // TODO: -T arguments for files
  706. components.append("\"\(URL.absoluteString!)\"")
  707. return join(" \\\n\t", components)
  708. }
  709. public var debugDescription: String {
  710. return self.cURLRepresentation()
  711. }
  712. }
  713. // MARK: - Response Serializers
  714. // MARK: String
  715. extension Request {
  716. public class func stringResponseSerializer(encoding: NSStringEncoding = NSUTF8StringEncoding) -> Serializer {
  717. return { (_, _, data) in
  718. let string = NSString(data: data!, encoding: encoding)
  719. return (string, nil)
  720. }
  721. }
  722. public func responseString(completionHandler: (NSURLRequest, NSHTTPURLResponse?, String?, NSError?) -> Void) -> Self {
  723. return responseString(completionHandler: completionHandler)
  724. }
  725. public func responseString(encoding: NSStringEncoding = NSUTF8StringEncoding, completionHandler: (NSURLRequest, NSHTTPURLResponse?, String?, NSError?) -> Void) -> Self {
  726. return response(serializer: Request.stringResponseSerializer(encoding: encoding), completionHandler: { request, response, string, error in
  727. completionHandler(request, response, string as? String, error)
  728. })
  729. }
  730. }
  731. // MARK: JSON
  732. extension Request {
  733. public class func JSONResponseSerializer(options: NSJSONReadingOptions = .AllowFragments) -> Serializer {
  734. return { (request, response, data) in
  735. var serializationError: NSError?
  736. let JSON: AnyObject? = NSJSONSerialization.JSONObjectWithData(data!, options: options, error: &serializationError)
  737. return (JSON, serializationError)
  738. }
  739. }
  740. public func responseJSON(completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Self {
  741. return responseJSON(completionHandler: completionHandler)
  742. }
  743. public func responseJSON(options: NSJSONReadingOptions = .AllowFragments, completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Self {
  744. return response(serializer: Request.JSONResponseSerializer(options: options), completionHandler: { (request, response, JSON, error) in
  745. completionHandler(request, response, JSON, error)
  746. })
  747. }
  748. }
  749. // MARK: Property List
  750. extension Request {
  751. public class func propertyListResponseSerializer(options: NSPropertyListReadOptions = 0) -> Serializer {
  752. return { (request, response, data) in
  753. var propertyListSerializationError: NSError?
  754. let plist: AnyObject? = NSPropertyListSerialization.propertyListWithData(data!, options: options, format: nil, error: &propertyListSerializationError)
  755. return (plist, propertyListSerializationError)
  756. }
  757. }
  758. public func responsePropertyList(completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Self {
  759. return responsePropertyList(completionHandler: completionHandler)
  760. }
  761. public func responsePropertyList(options: NSPropertyListReadOptions = 0, completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Self {
  762. return response(serializer: Request.propertyListResponseSerializer(options: options), completionHandler: { (request, response, plist, error) in
  763. completionHandler(request, response, plist, error)
  764. })
  765. }
  766. }
  767. // MARK: - Convenience
  768. private func URLRequest(method: Method, URLString: URLStringConvertible) -> NSURLRequest {
  769. let mutableURLRequest = NSMutableURLRequest(URL: NSURL(string: URLString.URLString))
  770. mutableURLRequest.HTTPMethod = method.toRaw()
  771. return mutableURLRequest
  772. }
  773. // MARK: Request
  774. public func request(method: Method, URLString: URLStringConvertible, parameters: [String: AnyObject]? = nil, encoding: ParameterEncoding = .URL) -> Request {
  775. return request(encoding.encode(URLRequest(method, URLString), parameters: parameters).0)
  776. }
  777. public func request(URLRequest: URLRequestConvertible) -> Request {
  778. return Manager.sharedInstance.request(URLRequest.URLRequest)
  779. }
  780. // MARK: Upload
  781. public func upload(method: Method, URLString: URLStringConvertible, file: NSURL) -> Request {
  782. return Manager.sharedInstance.upload(URLRequest(method, URLString), file: file)
  783. }
  784. public func upload(method: Method, URLString: URLStringConvertible, data: NSData) -> Request {
  785. return Manager.sharedInstance.upload(URLRequest(method, URLString), data: data)
  786. }
  787. public func upload(method: Method, URLString: URLStringConvertible, stream: NSInputStream) -> Request {
  788. return Manager.sharedInstance.upload(URLRequest(method, URLString), stream: stream)
  789. }
  790. // MARK: Download
  791. public func download(method: Method, URLString: URLStringConvertible, destination: (NSURL, NSHTTPURLResponse) -> (NSURL)) -> Request {
  792. return Manager.sharedInstance.download(URLRequest(method, URLString), destination: destination)
  793. }
  794. public func download(resumeData data: NSData, destination: (NSURL, NSHTTPURLResponse) -> (NSURL)) -> Request {
  795. return Manager.sharedInstance.download(data, destination: destination)
  796. }