Alamofire.swift 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951
  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. }
  351. return self
  352. }
  353. // MARK: Response
  354. public func response(completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Self {
  355. return response({ (request, response, data, error) in
  356. return (data, error)
  357. }, completionHandler: completionHandler)
  358. }
  359. 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 {
  360. dispatch_async(self.delegate.queue, {
  361. dispatch_async(dispatch_get_global_queue(priority, 0), {
  362. if var error = self.delegate.error {
  363. dispatch_async(queue ?? dispatch_get_main_queue(), {
  364. completionHandler(self.request, self.response, nil, error)
  365. })
  366. } else {
  367. let (responseObject: AnyObject?, serializationError: NSError?) = serializer(self.request, self.response, self.delegate.data, nil)
  368. dispatch_async(queue ?? dispatch_get_main_queue(), {
  369. completionHandler(self.request, self.response, responseObject, serializationError)
  370. })
  371. }
  372. })
  373. })
  374. return self
  375. }
  376. public func suspend() {
  377. self.task.suspend()
  378. }
  379. public func resume() {
  380. self.task.resume()
  381. }
  382. public func cancel() {
  383. if let downloadDelegate = self.delegate as? DownloadTaskDelegate {
  384. downloadDelegate.downloadTask.cancelByProducingResumeData { (data) in
  385. downloadDelegate.resumeData = data
  386. }
  387. } else {
  388. self.task.cancel()
  389. }
  390. }
  391. private class TaskDelegate: NSObject, NSURLSessionTaskDelegate {
  392. let task: NSURLSessionTask
  393. let queue: dispatch_queue_t?
  394. let progress: NSProgress
  395. var data: NSData! { return nil }
  396. private(set) var error: NSError?
  397. var taskWillPerformHTTPRedirection: ((NSURLSession!, NSURLSessionTask!, NSHTTPURLResponse!, NSURLRequest!) -> (NSURLRequest!))?
  398. var taskDidReceiveChallenge: ((NSURLSession!, NSURLSessionTask!, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))?
  399. var taskDidSendBodyData: ((NSURLSession!, NSURLSessionTask!, Int64, Int64, Int64) -> Void)?
  400. var taskNeedNewBodyStream: ((NSURLSession!, NSURLSessionTask!) -> (NSInputStream!))?
  401. init(task: NSURLSessionTask) {
  402. self.task = task
  403. self.progress = NSProgress(totalUnitCount: 0)
  404. let label: String = "com.alamofire.task-\(task.taskIdentifier)"
  405. let queue = dispatch_queue_create((label as NSString).UTF8String, DISPATCH_QUEUE_SERIAL)
  406. dispatch_suspend(queue)
  407. self.queue = queue
  408. }
  409. // MARK: NSURLSessionTaskDelegate
  410. func URLSession(session: NSURLSession!, task: NSURLSessionTask!, willPerformHTTPRedirection response: NSHTTPURLResponse!, newRequest request: NSURLRequest!, completionHandler: ((NSURLRequest!) -> Void)!) {
  411. var redirectRequest = request
  412. if self.taskWillPerformHTTPRedirection != nil {
  413. redirectRequest = self.taskWillPerformHTTPRedirection!(session, task, response, request)
  414. }
  415. completionHandler(redirectRequest)
  416. }
  417. func URLSession(session: NSURLSession!, task: NSURLSessionTask!, didReceiveChallenge challenge: NSURLAuthenticationChallenge!, completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential!) -> Void)!) {
  418. var disposition: NSURLSessionAuthChallengeDisposition = .PerformDefaultHandling
  419. var credential: NSURLCredential?
  420. if self.taskDidReceiveChallenge != nil {
  421. (disposition, credential) = self.taskDidReceiveChallenge!(session, task, challenge)
  422. } else {
  423. if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
  424. // TODO: Incorporate Trust Evaluation & TLS Chain Validation
  425. credential = NSURLCredential(forTrust: challenge.protectionSpace.serverTrust)
  426. disposition = .UseCredential
  427. }
  428. }
  429. completionHandler(disposition, credential)
  430. }
  431. func URLSession(session: NSURLSession!, task: NSURLSessionTask!, needNewBodyStream completionHandler: ((NSInputStream!) -> Void)!) {
  432. var bodyStream: NSInputStream?
  433. if self.taskNeedNewBodyStream != nil {
  434. bodyStream = self.taskNeedNewBodyStream!(session, task)
  435. }
  436. completionHandler(bodyStream)
  437. }
  438. func URLSession(session: NSURLSession!, task: NSURLSessionTask!, didCompleteWithError error: NSError!) {
  439. self.error = error
  440. dispatch_resume(self.queue)
  441. }
  442. }
  443. private class DataTaskDelegate: TaskDelegate, NSURLSessionDataDelegate {
  444. var dataTask: NSURLSessionDataTask! { return self.task as NSURLSessionDataTask }
  445. private var mutableData: NSMutableData
  446. override var data: NSData! {
  447. return self.mutableData
  448. }
  449. var dataTaskDidReceiveResponse: ((NSURLSession!, NSURLSessionDataTask!, NSURLResponse!) -> (NSURLSessionResponseDisposition))?
  450. var dataTaskDidBecomeDownloadTask: ((NSURLSession!, NSURLSessionDataTask!) -> Void)?
  451. var dataTaskDidReceiveData: ((NSURLSession!, NSURLSessionDataTask!, NSData!) -> Void)?
  452. var dataTaskWillCacheResponse: ((NSURLSession!, NSURLSessionDataTask!, NSCachedURLResponse!) -> (NSCachedURLResponse))?
  453. override init(task: NSURLSessionTask) {
  454. self.mutableData = NSMutableData()
  455. super.init(task: task)
  456. }
  457. // MARK: NSURLSessionDataDelegate
  458. func URLSession(session: NSURLSession!, dataTask: NSURLSessionDataTask!, didReceiveResponse response: NSURLResponse!, completionHandler: ((NSURLSessionResponseDisposition) -> Void)!) {
  459. var disposition: NSURLSessionResponseDisposition = .Allow
  460. if self.dataTaskDidReceiveResponse != nil {
  461. disposition = self.dataTaskDidReceiveResponse!(session, dataTask, response)
  462. }
  463. completionHandler(disposition)
  464. }
  465. func URLSession(session: NSURLSession!, dataTask: NSURLSessionDataTask!, didBecomeDownloadTask downloadTask: NSURLSessionDownloadTask!) {
  466. self.dataTaskDidBecomeDownloadTask?(session, dataTask)
  467. }
  468. func URLSession(session: NSURLSession!, dataTask: NSURLSessionDataTask!, didReceiveData data: NSData!) {
  469. self.dataTaskDidReceiveData?(session, dataTask, data)
  470. self.mutableData.appendData(data)
  471. }
  472. func URLSession(session: NSURLSession!, dataTask: NSURLSessionDataTask!, willCacheResponse proposedResponse: NSCachedURLResponse!, completionHandler: ((NSCachedURLResponse!) -> Void)!) {
  473. var cachedResponse = proposedResponse
  474. if self.dataTaskWillCacheResponse != nil {
  475. cachedResponse = self.dataTaskWillCacheResponse!(session, dataTask, proposedResponse)
  476. }
  477. completionHandler(cachedResponse)
  478. }
  479. }
  480. }
  481. // MARK: - Upload
  482. extension Manager {
  483. private enum Uploadable {
  484. case Data(NSURLRequest, NSData)
  485. case File(NSURLRequest, NSURL)
  486. case Stream(NSURLRequest, NSInputStream)
  487. }
  488. private func upload(uploadable: Uploadable) -> Request {
  489. var uploadTask: NSURLSessionUploadTask!
  490. var stream: NSInputStream?
  491. switch uploadable {
  492. case .Data(let request, let data):
  493. uploadTask = self.session.uploadTaskWithRequest(request, fromData: data)
  494. case .File(let request, let fileURL):
  495. uploadTask = self.session.uploadTaskWithRequest(request, fromFile: fileURL)
  496. case .Stream(let request, var stream):
  497. uploadTask = self.session.uploadTaskWithStreamedRequest(request)
  498. }
  499. let request = Request(session: self.session, task: uploadTask)
  500. if stream != nil {
  501. request.delegate.taskNeedNewBodyStream = { _, _ in
  502. return stream
  503. }
  504. }
  505. self.delegate[request.delegate.task] = request.delegate
  506. if self.automaticallyStartsRequests {
  507. request.resume()
  508. }
  509. return request
  510. }
  511. // MARK: File
  512. func upload(request: NSURLRequest, file: NSURL) -> Request {
  513. return upload(.File(request, file))
  514. }
  515. // MARK: Data
  516. func upload(request: NSURLRequest, data: NSData) -> Request {
  517. return upload(.Data(request, data))
  518. }
  519. // MARK: Stream
  520. func upload(request: NSURLRequest, stream: NSInputStream) -> Request {
  521. return upload(.Stream(request, stream))
  522. }
  523. }
  524. extension Request {
  525. private class UploadTaskDelegate: DataTaskDelegate {
  526. var uploadTask: NSURLSessionUploadTask! { return self.task as NSURLSessionUploadTask }
  527. var uploadProgress: ((Int64, Int64, Int64) -> Void)!
  528. // MARK: NSURLSessionTaskDelegate
  529. func URLSession(session: NSURLSession!, task: NSURLSessionTask!, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
  530. if self.uploadProgress != nil {
  531. self.uploadProgress(bytesSent, totalBytesSent, totalBytesExpectedToSend)
  532. }
  533. self.progress.totalUnitCount = totalBytesExpectedToSend
  534. self.progress.completedUnitCount = totalBytesSent
  535. }
  536. }
  537. }
  538. // MARK: - Download
  539. extension Manager {
  540. private enum Downloadable {
  541. case Request(NSURLRequest)
  542. case ResumeData(NSData)
  543. }
  544. private func download(downloadable: Downloadable, destination: (NSURL, NSHTTPURLResponse) -> (NSURL)) -> Request {
  545. var downloadTask: NSURLSessionDownloadTask!
  546. switch downloadable {
  547. case .Request(let request):
  548. downloadTask = self.session.downloadTaskWithRequest(request)
  549. case .ResumeData(let resumeData):
  550. downloadTask = self.session.downloadTaskWithResumeData(resumeData)
  551. }
  552. let request = Request(session: self.session, task: downloadTask)
  553. if let downloadDelegate = request.delegate as? Request.DownloadTaskDelegate {
  554. downloadDelegate.downloadTaskDidFinishDownloadingToURL = { (session, downloadTask, URL) in
  555. return destination(URL, downloadTask.response as NSHTTPURLResponse)
  556. }
  557. }
  558. self.delegate[request.delegate.task] = request.delegate
  559. if self.automaticallyStartsRequests {
  560. request.resume()
  561. }
  562. return request
  563. }
  564. // MARK: Request
  565. public func download(request: NSURLRequest, destination: (NSURL, NSHTTPURLResponse) -> (NSURL)) -> Request {
  566. return download(.Request(request), destination: destination)
  567. }
  568. // MARK: Resume Data
  569. public func download(resumeData: NSData, destination: (NSURL, NSHTTPURLResponse) -> (NSURL)) -> Request {
  570. return download(.ResumeData(resumeData), destination: destination)
  571. }
  572. }
  573. extension Request {
  574. public class func suggestedDownloadDestination(directory: NSSearchPathDirectory = .DocumentDirectory, domain: NSSearchPathDomainMask = .UserDomainMask) -> (NSURL, NSHTTPURLResponse) -> (NSURL) {
  575. return { (temporaryURL, response) -> (NSURL) in
  576. if let directoryURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0] as? NSURL {
  577. return directoryURL.URLByAppendingPathComponent(response.suggestedFilename!)
  578. }
  579. return temporaryURL
  580. }
  581. }
  582. private class DownloadTaskDelegate: TaskDelegate, NSURLSessionDownloadDelegate {
  583. var downloadTask: NSURLSessionDownloadTask! { return self.task as NSURLSessionDownloadTask }
  584. var downloadProgress: ((Int64, Int64, Int64) -> Void)?
  585. var resumeData: NSData!
  586. override var data: NSData! { return self.resumeData }
  587. var downloadTaskDidFinishDownloadingToURL: ((NSURLSession!, NSURLSessionDownloadTask!, NSURL) -> (NSURL))?
  588. var downloadTaskDidWriteData: ((NSURLSession!, NSURLSessionDownloadTask!, Int64, Int64, Int64) -> Void)?
  589. var downloadTaskDidResumeAtOffset: ((NSURLSession!, NSURLSessionDownloadTask!, Int64, Int64) -> Void)?
  590. // MARK: NSURLSessionDownloadDelegate
  591. func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL) {
  592. if self.downloadTaskDidFinishDownloadingToURL != nil {
  593. let destination = self.downloadTaskDidFinishDownloadingToURL!(session, downloadTask, location)
  594. var fileManagerError: NSError?
  595. NSFileManager.defaultManager().moveItemAtURL(location, toURL: destination, error: &fileManagerError)
  596. // TODO: NSNotification on failure
  597. }
  598. }
  599. func URLSession(session: NSURLSession!, downloadTask: NSURLSessionDownloadTask!, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
  600. self.downloadTaskDidWriteData?(session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite)
  601. self.downloadProgress?(bytesWritten, totalBytesWritten, totalBytesExpectedToWrite)
  602. self.progress.totalUnitCount = totalBytesExpectedToWrite
  603. self.progress.completedUnitCount = totalBytesWritten
  604. }
  605. func URLSession(session: NSURLSession!, downloadTask: NSURLSessionDownloadTask!, didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64) {
  606. self.downloadTaskDidResumeAtOffset?(session, downloadTask, fileOffset, expectedTotalBytes)
  607. self.progress.totalUnitCount = expectedTotalBytes
  608. self.progress.completedUnitCount = fileOffset
  609. }
  610. }
  611. }
  612. // MARK: - Printable
  613. extension Request: Printable {
  614. public var description: String {
  615. var description = "\(self.request.HTTPMethod) \(self.request.URL)"
  616. if self.response != nil {
  617. description += " (\(self.response?.statusCode))"
  618. }
  619. return description
  620. }
  621. }
  622. extension Request: DebugPrintable {
  623. func cURLRepresentation() -> String {
  624. var components: [String] = ["$ curl -i"]
  625. let URL = self.request.URL
  626. if self.request.HTTPMethod != "GET" {
  627. components.append("-X \(self.request.HTTPMethod)")
  628. }
  629. if let credentialStorage = self.session.configuration.URLCredentialStorage {
  630. let protectionSpace = NSURLProtectionSpace(host: URL.host!, port: URL.port ?? 0, `protocol`: URL.scheme, realm: URL.host, authenticationMethod: NSURLAuthenticationMethodHTTPBasic)
  631. if let credentials = credentialStorage.credentialsForProtectionSpace(protectionSpace)?.values.array {
  632. if !credentials.isEmpty {
  633. if let credential = credentials[0] as? NSURLCredential {
  634. components.append("-u \(credential.user):\(credential.password)")
  635. }
  636. }
  637. }
  638. }
  639. if let cookieStorage = self.session.configuration.HTTPCookieStorage {
  640. if let cookies = cookieStorage.cookiesForURL(URL) as? [NSHTTPCookie] {
  641. if !cookies.isEmpty {
  642. let string = cookies.reduce(""){ $0 + "\($1.name)=\($1.value);" }
  643. components.append("-b \"\(string.substringToIndex(string.endIndex.predecessor()))\"")
  644. }
  645. }
  646. }
  647. for (field, value) in self.request.allHTTPHeaderFields! {
  648. switch field {
  649. case "Cookie":
  650. continue
  651. default:
  652. components.append("-H \"\(field): \(value)\"")
  653. }
  654. }
  655. if let HTTPBody = self.request.HTTPBody {
  656. components.append("-d \"\(NSString(data: HTTPBody, encoding: NSUTF8StringEncoding))\"")
  657. }
  658. // TODO: -T arguments for files
  659. components.append("\"\(URL.absoluteString!)\"")
  660. return join(" \\\n\t", components)
  661. }
  662. public var debugDescription: String {
  663. return self.cURLRepresentation()
  664. }
  665. }
  666. // MARK: - Response Serializers
  667. // MARK: String
  668. extension Request {
  669. public class func stringResponseSerializer(encoding: NSStringEncoding = NSUTF8StringEncoding) -> (NSURLRequest, NSHTTPURLResponse?, NSData?, NSError?) -> (AnyObject?, NSError?) {
  670. return { (_, _, data, error) in
  671. let string = NSString(data: data!, encoding: encoding)
  672. return (string, error)
  673. }
  674. }
  675. public func responseString(completionHandler: (NSURLRequest, NSHTTPURLResponse?, String?, NSError?) -> Void) -> Self {
  676. return responseString(completionHandler: completionHandler)
  677. }
  678. public func responseString(encoding: NSStringEncoding = NSUTF8StringEncoding, completionHandler: (NSURLRequest, NSHTTPURLResponse?, String?, NSError?) -> Void) -> Self {
  679. return response(serializer: Request.stringResponseSerializer(encoding: encoding), completionHandler: { request, response, string, error in
  680. completionHandler(request, response, string as? String, error)
  681. })
  682. }
  683. }
  684. // MARK: JSON
  685. extension Request {
  686. public class func JSONResponseSerializer(options: NSJSONReadingOptions = .AllowFragments) -> (NSURLRequest, NSHTTPURLResponse?, NSData?, NSError?) -> (AnyObject?, NSError?) {
  687. return { (request, response, data, error) in
  688. var serializationError: NSError?
  689. let JSON: AnyObject! = NSJSONSerialization.JSONObjectWithData(data!, options: options, error: &serializationError)
  690. return (JSON, serializationError)
  691. }
  692. }
  693. public func responseJSON(completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Self {
  694. return responseJSON(completionHandler: completionHandler)
  695. }
  696. public func responseJSON(options: NSJSONReadingOptions = .AllowFragments, completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Self {
  697. return response(serializer: Request.JSONResponseSerializer(options: options), completionHandler: { (request, response, JSON, error) in
  698. completionHandler(request, response, JSON, error)
  699. })
  700. }
  701. }
  702. // MARK: Property List
  703. extension Request {
  704. public class func propertyListResponseSerializer(options: NSPropertyListReadOptions = 0) -> (NSURLRequest, NSHTTPURLResponse?, NSData?, NSError?) -> (AnyObject?, NSError?) {
  705. return { (request, response, data, error) in
  706. var propertyListSerializationError: NSError?
  707. let plist: AnyObject! = NSPropertyListSerialization.propertyListWithData(data!, options: options, format: nil, error: &propertyListSerializationError)
  708. return (plist, propertyListSerializationError)
  709. }
  710. }
  711. public func responsePropertyList(completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Self {
  712. return responsePropertyList(completionHandler: completionHandler)
  713. }
  714. public func responsePropertyList(options: NSPropertyListReadOptions = 0, completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Self {
  715. return response(serializer: Request.propertyListResponseSerializer(options: options), completionHandler: { (request, response, plist, error) in
  716. completionHandler(request, response, plist, error)
  717. })
  718. }
  719. }
  720. // MARK: - Convenience
  721. private func URLRequest(method: Method, URL: String) -> NSURLRequest {
  722. let mutableURLRequest = NSMutableURLRequest(URL: NSURL(string: URL))
  723. mutableURLRequest.HTTPMethod = method.toRaw()
  724. return mutableURLRequest
  725. }
  726. // MARK: Request
  727. public func request(method: Method, URL: String, parameters: [String: AnyObject]? = nil, encoding: ParameterEncoding = .URL) -> Request {
  728. return Manager.sharedInstance.request(encoding.encode(URLRequest(method, URL), parameters: parameters).0)
  729. }
  730. // MARK: Upload
  731. public func upload(method: Method, URL: String, file: NSURL) -> Request {
  732. return Manager.sharedInstance.upload(URLRequest(method, URL), file: file)
  733. }
  734. public func upload(method: Method, URL: String, data: NSData) -> Request {
  735. return Manager.sharedInstance.upload(URLRequest(method, URL), data: data)
  736. }
  737. public func upload(method: Method, URL: String, stream: NSInputStream) -> Request {
  738. return Manager.sharedInstance.upload(URLRequest(method, URL), stream: stream)
  739. }
  740. // MARK: Download
  741. public func download(method: Method, URL: String, destination: (NSURL, NSHTTPURLResponse) -> (NSURL)) -> Request {
  742. return Manager.sharedInstance.download(URLRequest(method, URL), destination: destination)
  743. }
  744. public func download(resumeData data: NSData, destination: (NSURL, NSHTTPURLResponse) -> (NSURL)) -> Request {
  745. return Manager.sharedInstance.download(data, destination: destination)
  746. }