Alamofire.swift 42 KB

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