2
0

Alamofire.swift 42 KB

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