Alamofire.swift 42 KB

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