2
0

Alamofire.swift 41 KB

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