Alamofire.swift 41 KB

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