Alamofire.swift 42 KB

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