Alamofire.swift 42 KB

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