Alamofire.swift 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040
  1. // Alamofire.swift
  2. //
  3. // Copyright (c) 2014 Alamofire (http://alamofire.org)
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. import Foundation
  23. // HTTP Method Definitions; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
  24. public enum Method: String {
  25. case OPTIONS = "OPTIONS"
  26. case GET = "GET"
  27. case HEAD = "HEAD"
  28. case POST = "POST"
  29. case PUT = "PUT"
  30. case PATCH = "PATCH"
  31. case DELETE = "DELETE"
  32. case TRACE = "TRACE"
  33. case CONNECT = "CONNECT"
  34. }
  35. public enum ParameterEncoding {
  36. case URL
  37. case JSON
  38. case PropertyList(NSPropertyListFormat, NSPropertyListWriteOptions)
  39. case Custom((NSURLRequest, [String: AnyObject]?) -> (NSURLRequest, NSError?))
  40. public func encode(request: NSURLRequest, parameters: [String: AnyObject]?) -> (NSURLRequest, NSError?) {
  41. if parameters == nil {
  42. return (request, nil)
  43. }
  44. var mutableRequest: NSMutableURLRequest! = request.mutableCopy() as NSMutableURLRequest
  45. var error: NSError? = nil
  46. switch self {
  47. case .URL:
  48. func query(parameters: [String: AnyObject]) -> String {
  49. var components: [(String, String)] = []
  50. for key in sorted(Array(parameters.keys), <) {
  51. let value: AnyObject! = parameters[key]
  52. components += queryComponents(key, value)
  53. }
  54. return join("&", components.map{"\($0)=\($1)"} as [String])
  55. }
  56. func encodesParametersInURL(method: Method) -> Bool {
  57. switch method {
  58. case .GET, .HEAD, .DELETE:
  59. return true
  60. default:
  61. return false
  62. }
  63. }
  64. if encodesParametersInURL(Method.fromRaw(request.HTTPMethod!)!) {
  65. let URLComponents = NSURLComponents(URL: mutableRequest.URL!, resolvingAgainstBaseURL: false)
  66. URLComponents.query = (URLComponents.query != nil ? URLComponents.query! + "&" : "") + query(parameters!)
  67. mutableRequest.URL = URLComponents.URL
  68. } else {
  69. if mutableRequest.valueForHTTPHeaderField("Content-Type") == nil {
  70. mutableRequest.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
  71. }
  72. mutableRequest.HTTPBody = query(parameters!).dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
  73. }
  74. case .JSON:
  75. let options = NSJSONWritingOptions.allZeros
  76. if let data = NSJSONSerialization.dataWithJSONObject(parameters!, options: options, error: &error) {
  77. mutableRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
  78. mutableRequest.HTTPBody = data
  79. }
  80. case .PropertyList(let (format, options)):
  81. if let data = NSPropertyListSerialization.dataWithPropertyList(parameters!, format: format, options: options, error: &error) {
  82. mutableRequest.setValue("application/x-plist", forHTTPHeaderField: "Content-Type")
  83. mutableRequest.HTTPBody = data
  84. }
  85. case .Custom(let closure):
  86. return closure(request, parameters)
  87. }
  88. return (mutableRequest, error)
  89. }
  90. 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 absoluteString!
  118. }
  119. }
  120. extension NSURLComponents: URLStringConvertible {
  121. public var URLString: String {
  122. return URL!.URLString
  123. }
  124. }
  125. extension NSURLRequest: URLStringConvertible {
  126. public var URLString: String {
  127. return 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. private let delegate: SessionDelegate
  185. public let session: NSURLSession!
  186. let operationQueue: NSOperationQueue = NSOperationQueue()
  187. var startRequestsImmediately: Bool = true
  188. required public init(configuration: NSURLSessionConfiguration? = nil) {
  189. self.delegate = SessionDelegate()
  190. self.session = NSURLSession(configuration: configuration, delegate: delegate, delegateQueue: 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: session, task: dataTask!)
  202. delegate[request.delegate.task] = request.delegate
  203. if startRequestsImmediately {
  204. request.resume()
  205. }
  206. return request
  207. }
  208. private 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 subdelegates[task.taskIdentifier]
  213. }
  214. set {
  215. 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. sessionDidBecomeInvalidWithError?(session, error)
  239. }
  240. func URLSession(session: NSURLSession!, didReceiveChallenge challenge: NSURLAuthenticationChallenge!, completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential!) -> Void)!) {
  241. if sessionDidReceiveChallenge != nil {
  242. completionHandler(sessionDidReceiveChallenge!(session, challenge))
  243. } else {
  244. completionHandler(.PerformDefaultHandling, nil)
  245. }
  246. }
  247. func URLSessionDidFinishEventsForBackgroundURLSession(session: NSURLSession!) {
  248. 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 taskWillPerformHTTPRedirection != nil {
  254. redirectRequest = 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. 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. self[task] = nil
  279. }
  280. }
  281. // MARK: NSURLSessionDataDelegate
  282. func URLSession(session: NSURLSession!, dataTask: NSURLSessionDataTask!, didReceiveResponse response: NSURLResponse!, completionHandler: ((NSURLSessionResponseDisposition) -> Void)!) {
  283. var disposition: NSURLSessionResponseDisposition = .Allow
  284. if dataTaskDidReceiveResponse != nil {
  285. disposition = dataTaskDidReceiveResponse!(session, dataTask, response)
  286. }
  287. completionHandler(disposition)
  288. }
  289. func URLSession(session: NSURLSession!, dataTask: NSURLSessionDataTask!, didBecomeDownloadTask downloadTask: NSURLSessionDownloadTask!) {
  290. let downloadDelegate = Request.DownloadTaskDelegate(task: downloadTask)
  291. self[downloadTask] = downloadDelegate
  292. }
  293. func URLSession(session: NSURLSession!, dataTask: NSURLSessionDataTask!, didReceiveData data: NSData!) {
  294. if let delegate = self[dataTask] as? Request.DataTaskDelegate {
  295. delegate.URLSession(session, dataTask: dataTask, didReceiveData: data)
  296. }
  297. dataTaskDidReceiveData?(session, dataTask, data)
  298. }
  299. func URLSession(session: NSURLSession!, dataTask: NSURLSessionDataTask!, willCacheResponse proposedResponse: NSCachedURLResponse!, completionHandler: ((NSCachedURLResponse!) -> Void)!) {
  300. var cachedResponse = proposedResponse
  301. if dataTaskWillCacheResponse != nil {
  302. cachedResponse = dataTaskWillCacheResponse!(session, dataTask, proposedResponse)
  303. }
  304. completionHandler(cachedResponse)
  305. }
  306. // MARK: NSURLSessionDownloadDelegate
  307. func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL) {
  308. if let delegate = self[downloadTask] as? Request.DownloadTaskDelegate {
  309. delegate.URLSession(session, downloadTask: downloadTask, didFinishDownloadingToURL: location)
  310. }
  311. downloadTaskDidFinishDownloadingToURL?(session, downloadTask, location)
  312. }
  313. func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
  314. if let delegate = self[downloadTask] as? Request.DownloadTaskDelegate {
  315. delegate.URLSession(session, downloadTask: downloadTask, didWriteData: bytesWritten, totalBytesWritten: totalBytesWritten, totalBytesExpectedToWrite: totalBytesExpectedToWrite)
  316. }
  317. downloadTaskDidWriteData?(session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite)
  318. }
  319. func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64) {
  320. if let delegate = self[downloadTask] as? Request.DownloadTaskDelegate {
  321. delegate.URLSession(session, downloadTask: downloadTask, didResumeAtOffset: fileOffset, expectedTotalBytes: expectedTotalBytes)
  322. }
  323. downloadTaskDidResumeAtOffset?(session, downloadTask, fileOffset, expectedTotalBytes)
  324. }
  325. // MARK: NSObject
  326. override func respondsToSelector(selector: Selector) -> Bool {
  327. switch selector {
  328. case "URLSession:didBecomeInvalidWithError:":
  329. return (sessionDidBecomeInvalidWithError != nil)
  330. case "URLSession:didReceiveChallenge:completionHandler:":
  331. return (sessionDidReceiveChallenge != nil)
  332. case "URLSessionDidFinishEventsForBackgroundURLSession:":
  333. return (sessionDidFinishEventsForBackgroundURLSession != nil)
  334. case "URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:":
  335. return (taskWillPerformHTTPRedirection != nil)
  336. case "URLSession:dataTask:didReceiveResponse:completionHandler:":
  337. return (dataTaskDidReceiveResponse != nil)
  338. case "URLSession:dataTask:willCacheResponse:completionHandler:":
  339. return (dataTaskWillCacheResponse != nil)
  340. default:
  341. return self.dynamicType.instancesRespondToSelector(selector)
  342. }
  343. }
  344. }
  345. }
  346. // MARK: -
  347. public class Request {
  348. private let delegate: TaskDelegate
  349. public let session: NSURLSession
  350. public var task: NSURLSessionTask { return delegate.task }
  351. public var request: NSURLRequest { return task.originalRequest }
  352. public var response: NSHTTPURLResponse? { return task.response as? NSHTTPURLResponse }
  353. public var progress: NSProgress? { return delegate.progress }
  354. private init(session: NSURLSession, task: NSURLSessionTask) {
  355. self.session = session
  356. switch task {
  357. case is NSURLSessionUploadTask:
  358. self.delegate = UploadTaskDelegate(task: task)
  359. case is NSURLSessionDataTask:
  360. self.delegate = DataTaskDelegate(task: task)
  361. case is NSURLSessionDownloadTask:
  362. self.delegate = DownloadTaskDelegate(task: task)
  363. default:
  364. self.delegate = TaskDelegate(task: task)
  365. }
  366. }
  367. // MARK: Authentication
  368. public func authenticate(#user: String, password: String) -> Self {
  369. let credential = NSURLCredential(user: user, password: password, persistence: .ForSession)
  370. return authenticate(usingCredential: credential)
  371. }
  372. public func authenticate(usingCredential credential: NSURLCredential) -> Self {
  373. delegate.credential = credential
  374. return self
  375. }
  376. // MARK: Progress
  377. public func progress(closure: ((Int64, Int64, Int64) -> Void)? = nil) -> Self {
  378. if let uploadDelegate = delegate as? UploadTaskDelegate {
  379. uploadDelegate.uploadProgress = closure
  380. } else if let dataDelegate = delegate as? DataTaskDelegate {
  381. dataDelegate.dataProgress = closure
  382. } else if let downloadDelegate = delegate as? DownloadTaskDelegate {
  383. downloadDelegate.downloadProgress = closure
  384. }
  385. return self
  386. }
  387. // MARK: Response
  388. public typealias Serializer = (NSURLRequest, NSHTTPURLResponse?, NSData?) -> (AnyObject?, NSError?)
  389. public class func responseDataSerializer() -> Serializer {
  390. return { (request, response, data) in
  391. return (data, nil)
  392. }
  393. }
  394. public func response(completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Self {
  395. return response(Request.responseDataSerializer(), completionHandler: completionHandler)
  396. }
  397. public func response(priority: Int = DISPATCH_QUEUE_PRIORITY_DEFAULT, queue: dispatch_queue_t? = nil, serializer: Serializer, completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Self {
  398. dispatch_async(delegate.queue, {
  399. dispatch_async(dispatch_get_global_queue(priority, 0), {
  400. if var error = self.delegate.error {
  401. dispatch_async(queue ?? dispatch_get_main_queue(), {
  402. completionHandler(self.request, self.response, nil, error)
  403. })
  404. } else {
  405. let (responseObject: AnyObject?, serializationError: NSError?) = serializer(self.request, self.response, self.delegate.data)
  406. dispatch_async(queue ?? dispatch_get_main_queue(), {
  407. completionHandler(self.request, self.response, responseObject, serializationError)
  408. })
  409. }
  410. })
  411. })
  412. return self
  413. }
  414. public func suspend() {
  415. task.suspend()
  416. }
  417. public func resume() {
  418. task.resume()
  419. }
  420. public func cancel() {
  421. if let downloadDelegate = delegate as? DownloadTaskDelegate {
  422. downloadDelegate.downloadTask.cancelByProducingResumeData { (data) in
  423. downloadDelegate.resumeData = data
  424. }
  425. } else {
  426. task.cancel()
  427. }
  428. }
  429. private class TaskDelegate: NSObject, NSURLSessionTaskDelegate {
  430. let task: NSURLSessionTask
  431. let queue: dispatch_queue_t
  432. let progress: NSProgress
  433. var data: NSData? { return nil }
  434. private(set) var error: NSError?
  435. var credential: NSURLCredential?
  436. var taskWillPerformHTTPRedirection: ((NSURLSession!, NSURLSessionTask!, NSHTTPURLResponse!, NSURLRequest!) -> (NSURLRequest!))?
  437. var taskDidReceiveChallenge: ((NSURLSession!, NSURLSessionTask!, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))?
  438. var taskDidSendBodyData: ((NSURLSession!, NSURLSessionTask!, Int64, Int64, Int64) -> Void)?
  439. var taskNeedNewBodyStream: ((NSURLSession!, NSURLSessionTask!) -> (NSInputStream!))?
  440. init(task: NSURLSessionTask) {
  441. self.task = task
  442. self.progress = NSProgress(totalUnitCount: 0)
  443. let label: String = "com.alamofire.task-\(task.taskIdentifier)"
  444. let queue = dispatch_queue_create((label as NSString).UTF8String, DISPATCH_QUEUE_SERIAL)
  445. dispatch_suspend(queue)
  446. self.queue = queue
  447. }
  448. // MARK: NSURLSessionTaskDelegate
  449. func URLSession(session: NSURLSession!, task: NSURLSessionTask!, willPerformHTTPRedirection response: NSHTTPURLResponse!, newRequest request: NSURLRequest!, completionHandler: ((NSURLRequest!) -> Void)!) {
  450. var redirectRequest = request
  451. if taskWillPerformHTTPRedirection != nil {
  452. redirectRequest = taskWillPerformHTTPRedirection!(session, task, response, request)
  453. }
  454. completionHandler(redirectRequest)
  455. }
  456. func URLSession(session: NSURLSession!, task: NSURLSessionTask!, didReceiveChallenge challenge: NSURLAuthenticationChallenge!, completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential!) -> Void)!) {
  457. var disposition: NSURLSessionAuthChallengeDisposition = .PerformDefaultHandling
  458. var credential: NSURLCredential?
  459. if taskDidReceiveChallenge != nil {
  460. (disposition, credential) = taskDidReceiveChallenge!(session, task, challenge)
  461. } else {
  462. if challenge.previousFailureCount > 0 {
  463. disposition = .CancelAuthenticationChallenge
  464. } else {
  465. // TODO: Incorporate Trust Evaluation & TLS Chain Validation
  466. switch challenge.protectionSpace.authenticationMethod! {
  467. case NSURLAuthenticationMethodServerTrust:
  468. credential = NSURLCredential(forTrust: challenge.protectionSpace.serverTrust)
  469. default:
  470. credential = credential ?? session.configuration.URLCredentialStorage?.defaultCredentialForProtectionSpace(challenge.protectionSpace)
  471. }
  472. if credential != nil {
  473. disposition = .UseCredential
  474. }
  475. }
  476. }
  477. completionHandler(disposition, credential)
  478. }
  479. func URLSession(session: NSURLSession!, task: NSURLSessionTask!, needNewBodyStream completionHandler: ((NSInputStream!) -> Void)!) {
  480. var bodyStream: NSInputStream?
  481. if taskNeedNewBodyStream != nil {
  482. bodyStream = taskNeedNewBodyStream!(session, task)
  483. }
  484. completionHandler(bodyStream)
  485. }
  486. func URLSession(session: NSURLSession!, task: NSURLSessionTask!, didCompleteWithError error: NSError!) {
  487. self.error = error
  488. dispatch_resume(queue)
  489. }
  490. }
  491. private class DataTaskDelegate: TaskDelegate, NSURLSessionDataDelegate {
  492. var dataTask: NSURLSessionDataTask! { return task as NSURLSessionDataTask }
  493. private var mutableData: NSMutableData
  494. override var data: NSData? {
  495. return mutableData
  496. }
  497. private var expectedContentLength: Int64?
  498. var dataTaskDidReceiveResponse: ((NSURLSession!, NSURLSessionDataTask!, NSURLResponse!) -> (NSURLSessionResponseDisposition))?
  499. var dataTaskDidBecomeDownloadTask: ((NSURLSession!, NSURLSessionDataTask!) -> Void)?
  500. var dataTaskDidReceiveData: ((NSURLSession!, NSURLSessionDataTask!, NSData!) -> Void)?
  501. var dataTaskWillCacheResponse: ((NSURLSession!, NSURLSessionDataTask!, NSCachedURLResponse!) -> (NSCachedURLResponse))?
  502. var dataProgress: ((bytesReceived: Int64, totalBytesReceived: Int64, totalBytesExpectedToReceive: Int64) -> Void)?
  503. override init(task: NSURLSessionTask) {
  504. self.mutableData = NSMutableData()
  505. super.init(task: task)
  506. }
  507. // MARK: NSURLSessionDataDelegate
  508. func URLSession(session: NSURLSession!, dataTask: NSURLSessionDataTask!, didReceiveResponse response: NSURLResponse!, completionHandler: ((NSURLSessionResponseDisposition) -> Void)!) {
  509. var disposition: NSURLSessionResponseDisposition = .Allow
  510. expectedContentLength = response.expectedContentLength
  511. if dataTaskDidReceiveResponse != nil {
  512. disposition = dataTaskDidReceiveResponse!(session, dataTask, response)
  513. }
  514. completionHandler(disposition)
  515. }
  516. func URLSession(session: NSURLSession!, dataTask: NSURLSessionDataTask!, didBecomeDownloadTask downloadTask: NSURLSessionDownloadTask!) {
  517. dataTaskDidBecomeDownloadTask?(session, dataTask)
  518. }
  519. func URLSession(session: NSURLSession!, dataTask: NSURLSessionDataTask!, didReceiveData data: NSData!) {
  520. dataTaskDidReceiveData?(session, dataTask, data)
  521. mutableData.appendData(data)
  522. if let expectedContentLength = dataTask?.response?.expectedContentLength {
  523. dataProgress?(bytesReceived: Int64(data.length), totalBytesReceived: Int64(mutableData.length), totalBytesExpectedToReceive: expectedContentLength)
  524. }
  525. }
  526. func URLSession(session: NSURLSession!, dataTask: NSURLSessionDataTask!, willCacheResponse proposedResponse: NSCachedURLResponse!, completionHandler: ((NSCachedURLResponse!) -> Void)!) {
  527. var cachedResponse = proposedResponse
  528. if dataTaskWillCacheResponse != nil {
  529. cachedResponse = dataTaskWillCacheResponse!(session, dataTask, proposedResponse)
  530. }
  531. completionHandler(cachedResponse)
  532. }
  533. }
  534. }
  535. // MARK: - Upload
  536. extension Manager {
  537. private enum Uploadable {
  538. case Data(NSURLRequest, NSData)
  539. case File(NSURLRequest, NSURL)
  540. case Stream(NSURLRequest, NSInputStream)
  541. }
  542. private func upload(uploadable: Uploadable) -> Request {
  543. var uploadTask: NSURLSessionUploadTask!
  544. var stream: NSInputStream?
  545. switch uploadable {
  546. case .Data(let request, let data):
  547. uploadTask = session.uploadTaskWithRequest(request, fromData: data)
  548. case .File(let request, let fileURL):
  549. uploadTask = session.uploadTaskWithRequest(request, fromFile: fileURL)
  550. case .Stream(let request, var stream):
  551. uploadTask = session.uploadTaskWithStreamedRequest(request)
  552. }
  553. let request = Request(session: session, task: uploadTask)
  554. if stream != nil {
  555. request.delegate.taskNeedNewBodyStream = { _, _ in
  556. return stream
  557. }
  558. }
  559. delegate[request.delegate.task] = request.delegate
  560. if startRequestsImmediately {
  561. request.resume()
  562. }
  563. return request
  564. }
  565. // MARK: File
  566. func upload(request: NSURLRequest, file: NSURL) -> Request {
  567. return upload(.File(request, file))
  568. }
  569. // MARK: Data
  570. func upload(request: NSURLRequest, data: NSData) -> Request {
  571. return upload(.Data(request, data))
  572. }
  573. // MARK: Stream
  574. func upload(request: NSURLRequest, stream: NSInputStream) -> Request {
  575. return upload(.Stream(request, stream))
  576. }
  577. }
  578. extension Request {
  579. private class UploadTaskDelegate: DataTaskDelegate {
  580. var uploadTask: NSURLSessionUploadTask! { return task as NSURLSessionUploadTask }
  581. var uploadProgress: ((Int64, Int64, Int64) -> Void)!
  582. // MARK: NSURLSessionTaskDelegate
  583. func URLSession(session: NSURLSession!, task: NSURLSessionTask!, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
  584. if uploadProgress != nil {
  585. uploadProgress(bytesSent, totalBytesSent, totalBytesExpectedToSend)
  586. }
  587. progress.totalUnitCount = totalBytesExpectedToSend
  588. progress.completedUnitCount = totalBytesSent
  589. }
  590. }
  591. }
  592. // MARK: - Download
  593. extension Manager {
  594. private enum Downloadable {
  595. case Request(NSURLRequest)
  596. case ResumeData(NSData)
  597. }
  598. private func download(downloadable: Downloadable, destination: (NSURL, NSHTTPURLResponse) -> (NSURL)) -> Request {
  599. var downloadTask: NSURLSessionDownloadTask!
  600. switch downloadable {
  601. case .Request(let request):
  602. downloadTask = session.downloadTaskWithRequest(request)
  603. case .ResumeData(let resumeData):
  604. downloadTask = session.downloadTaskWithResumeData(resumeData)
  605. }
  606. let request = Request(session: session, task: downloadTask)
  607. if let downloadDelegate = request.delegate as? Request.DownloadTaskDelegate {
  608. downloadDelegate.downloadTaskDidFinishDownloadingToURL = { (session, downloadTask, URL) in
  609. return destination(URL, downloadTask.response as NSHTTPURLResponse)
  610. }
  611. }
  612. delegate[request.delegate.task] = request.delegate
  613. if startRequestsImmediately {
  614. request.resume()
  615. }
  616. return request
  617. }
  618. // MARK: Request
  619. public func download(request: NSURLRequest, destination: (NSURL, NSHTTPURLResponse) -> (NSURL)) -> Request {
  620. return download(.Request(request), destination: destination)
  621. }
  622. // MARK: Resume Data
  623. public func download(resumeData: NSData, destination: (NSURL, NSHTTPURLResponse) -> (NSURL)) -> Request {
  624. return download(.ResumeData(resumeData), destination: destination)
  625. }
  626. }
  627. extension Request {
  628. public class func suggestedDownloadDestination(directory: NSSearchPathDirectory = .DocumentDirectory, domain: NSSearchPathDomainMask = .UserDomainMask) -> (NSURL, NSHTTPURLResponse) -> (NSURL) {
  629. return { (temporaryURL, response) -> (NSURL) in
  630. if let directoryURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0] as? NSURL {
  631. return directoryURL.URLByAppendingPathComponent(response.suggestedFilename!)
  632. }
  633. return temporaryURL
  634. }
  635. }
  636. private class DownloadTaskDelegate: TaskDelegate, NSURLSessionDownloadDelegate {
  637. var downloadTask: NSURLSessionDownloadTask! { return task as NSURLSessionDownloadTask }
  638. var downloadProgress: ((Int64, Int64, Int64) -> Void)?
  639. var resumeData: NSData?
  640. override var data: NSData? { return resumeData }
  641. var downloadTaskDidFinishDownloadingToURL: ((NSURLSession!, NSURLSessionDownloadTask!, NSURL) -> (NSURL))?
  642. var downloadTaskDidWriteData: ((NSURLSession!, NSURLSessionDownloadTask!, Int64, Int64, Int64) -> Void)?
  643. var downloadTaskDidResumeAtOffset: ((NSURLSession!, NSURLSessionDownloadTask!, Int64, Int64) -> Void)?
  644. // MARK: NSURLSessionDownloadDelegate
  645. func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL) {
  646. if downloadTaskDidFinishDownloadingToURL != nil {
  647. let destination = downloadTaskDidFinishDownloadingToURL!(session, downloadTask, location)
  648. var fileManagerError: NSError?
  649. NSFileManager.defaultManager().moveItemAtURL(location, toURL: destination, error: &fileManagerError)
  650. if fileManagerError != nil {
  651. error = fileManagerError
  652. }
  653. }
  654. }
  655. func URLSession(session: NSURLSession!, downloadTask: NSURLSessionDownloadTask!, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
  656. downloadTaskDidWriteData?(session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite)
  657. downloadProgress?(bytesWritten, totalBytesWritten, totalBytesExpectedToWrite)
  658. progress.totalUnitCount = totalBytesExpectedToWrite
  659. progress.completedUnitCount = totalBytesWritten
  660. }
  661. func URLSession(session: NSURLSession!, downloadTask: NSURLSessionDownloadTask!, didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64) {
  662. downloadTaskDidResumeAtOffset?(session, downloadTask, fileOffset, expectedTotalBytes)
  663. progress.totalUnitCount = expectedTotalBytes
  664. progress.completedUnitCount = fileOffset
  665. }
  666. }
  667. }
  668. // MARK: - Printable
  669. extension Request: Printable {
  670. public var description: String {
  671. var components: [String] = []
  672. if request.HTTPMethod != nil {
  673. components.append(request.HTTPMethod!)
  674. }
  675. components.append(request.URL.absoluteString!)
  676. if response != nil {
  677. components.append("(\(response!.statusCode))")
  678. }
  679. return join(" ", components)
  680. }
  681. }
  682. extension Request: DebugPrintable {
  683. func cURLRepresentation() -> String {
  684. var components: [String] = ["$ curl -i"]
  685. let URL = request.URL
  686. if request.HTTPMethod != nil && request.HTTPMethod != "GET" {
  687. components.append("-X \(request.HTTPMethod!)")
  688. }
  689. if let credentialStorage = session.configuration.URLCredentialStorage {
  690. let protectionSpace = NSURLProtectionSpace(host: URL.host!, port: URL.port ?? 0, `protocol`: URL.scheme, realm: URL.host, authenticationMethod: NSURLAuthenticationMethodHTTPBasic)
  691. if let credentials = credentialStorage.credentialsForProtectionSpace(protectionSpace)?.values.array {
  692. for credential: NSURLCredential in (credentials as [NSURLCredential]) {
  693. components.append("-u \(credential.user):\(credential.password)")
  694. }
  695. } else {
  696. if let credential = delegate.credential {
  697. components.append("-u \(credential.user):\(credential.password)")
  698. }
  699. }
  700. }
  701. if let cookieStorage = session.configuration.HTTPCookieStorage {
  702. if let cookies = cookieStorage.cookiesForURL(URL) as? [NSHTTPCookie] {
  703. if !cookies.isEmpty {
  704. let string = cookies.reduce(""){ $0 + "\($1.name)=\($1.value);" }
  705. components.append("-b \"\(string.substringToIndex(string.endIndex.predecessor()))\"")
  706. }
  707. }
  708. }
  709. for (field, value) in request.allHTTPHeaderFields! {
  710. switch field {
  711. case "Cookie":
  712. continue
  713. default:
  714. components.append("-H \"\(field): \(value)\"")
  715. }
  716. }
  717. if let HTTPBody = request.HTTPBody {
  718. components.append("-d \"\(NSString(data: HTTPBody, encoding: NSUTF8StringEncoding))\"")
  719. }
  720. components.append("\"\(URL.absoluteString!)\"")
  721. return join(" \\\n\t", components)
  722. }
  723. public var debugDescription: String {
  724. return cURLRepresentation()
  725. }
  726. }
  727. // MARK: - Response Serializers
  728. // MARK: String
  729. extension Request {
  730. public class func stringResponseSerializer(encoding: NSStringEncoding = NSUTF8StringEncoding) -> Serializer {
  731. return { (_, _, data) in
  732. let string = NSString(data: data!, encoding: encoding)
  733. return (string, nil)
  734. }
  735. }
  736. public func responseString(completionHandler: (NSURLRequest, NSHTTPURLResponse?, String?, NSError?) -> Void) -> Self {
  737. return responseString(completionHandler: completionHandler)
  738. }
  739. public func responseString(encoding: NSStringEncoding = NSUTF8StringEncoding, completionHandler: (NSURLRequest, NSHTTPURLResponse?, String?, NSError?) -> Void) -> Self {
  740. return response(serializer: Request.stringResponseSerializer(encoding: encoding), completionHandler: { request, response, string, error in
  741. completionHandler(request, response, string as? String, error)
  742. })
  743. }
  744. }
  745. // MARK: JSON
  746. extension Request {
  747. public class func JSONResponseSerializer(options: NSJSONReadingOptions = .AllowFragments) -> Serializer {
  748. return { (request, response, data) in
  749. var serializationError: NSError?
  750. let JSON: AnyObject? = NSJSONSerialization.JSONObjectWithData(data!, options: options, error: &serializationError)
  751. return (JSON, serializationError)
  752. }
  753. }
  754. public func responseJSON(completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Self {
  755. return responseJSON(completionHandler: completionHandler)
  756. }
  757. public func responseJSON(options: NSJSONReadingOptions = .AllowFragments, completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Self {
  758. return response(serializer: Request.JSONResponseSerializer(options: options), completionHandler: { (request, response, JSON, error) in
  759. completionHandler(request, response, JSON, error)
  760. })
  761. }
  762. }
  763. // MARK: Property List
  764. extension Request {
  765. public class func propertyListResponseSerializer(options: NSPropertyListReadOptions = 0) -> Serializer {
  766. return { (request, response, data) in
  767. var propertyListSerializationError: NSError?
  768. let plist: AnyObject? = NSPropertyListSerialization.propertyListWithData(data!, options: options, format: nil, error: &propertyListSerializationError)
  769. return (plist, propertyListSerializationError)
  770. }
  771. }
  772. public func responsePropertyList(completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Self {
  773. return responsePropertyList(completionHandler: completionHandler)
  774. }
  775. public func responsePropertyList(options: NSPropertyListReadOptions = 0, completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Self {
  776. return response(serializer: Request.propertyListResponseSerializer(options: options), completionHandler: { (request, response, plist, error) in
  777. completionHandler(request, response, plist, error)
  778. })
  779. }
  780. }
  781. // MARK: - Convenience
  782. private func URLRequest(method: Method, URLString: URLStringConvertible) -> NSURLRequest {
  783. let mutableURLRequest = NSMutableURLRequest(URL: NSURL(string: URLString.URLString))
  784. mutableURLRequest.HTTPMethod = method.toRaw()
  785. return mutableURLRequest
  786. }
  787. // MARK: Request
  788. public func request(method: Method, URLString: URLStringConvertible, parameters: [String: AnyObject]? = nil, encoding: ParameterEncoding = .URL) -> Request {
  789. return request(encoding.encode(URLRequest(method, URLString), parameters: parameters).0)
  790. }
  791. public func request(URLRequest: URLRequestConvertible) -> Request {
  792. return Manager.sharedInstance.request(URLRequest.URLRequest)
  793. }
  794. // MARK: Upload
  795. public func upload(method: Method, URLString: URLStringConvertible, file: NSURL) -> Request {
  796. return Manager.sharedInstance.upload(URLRequest(method, URLString), file: file)
  797. }
  798. public func upload(method: Method, URLString: URLStringConvertible, data: NSData) -> Request {
  799. return Manager.sharedInstance.upload(URLRequest(method, URLString), data: data)
  800. }
  801. public func upload(method: Method, URLString: URLStringConvertible, stream: NSInputStream) -> Request {
  802. return Manager.sharedInstance.upload(URLRequest(method, URLString), stream: stream)
  803. }
  804. // MARK: Download
  805. public func download(method: Method, URLString: URLStringConvertible, destination: (NSURL, NSHTTPURLResponse) -> (NSURL)) -> Request {
  806. return Manager.sharedInstance.download(URLRequest(method, URLString), destination: destination)
  807. }
  808. public func download(resumeData data: NSData, destination: (NSURL, NSHTTPURLResponse) -> (NSURL)) -> Request {
  809. return Manager.sharedInstance.download(data, destination: destination)
  810. }