Alamofire.swift 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994
  1. // Alamofire.swift
  2. //
  3. // Copyright (c) 2014 Alamofire (http://alamofire.org)
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. import Foundation
  23. // HTTP Method Definitions; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
  24. public enum Method: String {
  25. case OPTIONS = "OPTIONS"
  26. case GET = "GET"
  27. case HEAD = "HEAD"
  28. case POST = "POST"
  29. case PUT = "PUT"
  30. case PATCH = "PATCH"
  31. case DELETE = "DELETE"
  32. case TRACE = "TRACE"
  33. case CONNECT = "CONNECT"
  34. }
  35. public enum ParameterEncoding {
  36. case URL
  37. case JSON//(NSJSONWritingOptions)
  38. case PropertyList(NSPropertyListFormat, NSPropertyListWriteOptions)
  39. case Custom((NSURLRequest, [String: AnyObject]?) -> (NSURLRequest, NSError?))
  40. public func encode(request: NSURLRequest, parameters: [String: AnyObject]?) -> (NSURLRequest, NSError?) {
  41. if parameters == nil {
  42. return (request, nil)
  43. }
  44. var mutableRequest: NSMutableURLRequest! = request.mutableCopy() as NSMutableURLRequest
  45. var error: NSError? = nil
  46. switch self {
  47. case .URL:
  48. func query(parameters: [String: AnyObject]) -> String {
  49. var components: [(String, String)] = []
  50. for key in sorted(Array(parameters.keys), <) {
  51. let value: AnyObject! = parameters[key]
  52. components += queryComponents(key, value)
  53. }
  54. return join("&", components.map{"\($0)=\($1)"} as [String])
  55. }
  56. func encodesParametersInURL(method: Method) -> Bool {
  57. switch method {
  58. case .GET, .HEAD, .DELETE:
  59. return true
  60. default:
  61. return false
  62. }
  63. }
  64. if encodesParametersInURL(Method.fromRaw(request.HTTPMethod!)!) {
  65. let URLComponents = NSURLComponents(URL: mutableRequest.URL!, resolvingAgainstBaseURL: false)
  66. URLComponents.query = (URLComponents.query != nil ? URLComponents.query! + "&" : "") + query(parameters!)
  67. mutableRequest.URL = URLComponents.URL
  68. } else {
  69. if mutableRequest.valueForHTTPHeaderField("Content-Type") == nil {
  70. mutableRequest.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
  71. }
  72. mutableRequest.HTTPBody = query(parameters!).dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
  73. }
  74. case .JSON://(let options):
  75. let options = NSJSONWritingOptions.allZeros
  76. if let data = NSJSONSerialization.dataWithJSONObject(parameters!, options: options, error: &error) {
  77. let charset = CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding))
  78. mutableRequest.setValue("application/json; charset=\(charset)", forHTTPHeaderField: "Content-Type")
  79. mutableRequest.HTTPBody = data
  80. }
  81. case .PropertyList(let (format, options)):
  82. if let data = NSPropertyListSerialization.dataWithPropertyList(parameters!, format: format, options: options, error: &error) {
  83. let charset = CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));
  84. mutableRequest.setValue("application/x-plist; charset=\(charset)", forHTTPHeaderField: "Content-Type")
  85. mutableRequest.HTTPBody = data
  86. }
  87. case .Custom(let closure):
  88. return closure(request, parameters)
  89. }
  90. return (mutableRequest, error)
  91. }
  92. private func queryComponents(key: String, _ value: AnyObject) -> [(String, String)] {
  93. var components: [(String, String)] = []
  94. if let dictionary = value as? [String: AnyObject] {
  95. for (nestedKey, value) in dictionary {
  96. components += queryComponents("\(key)[\(nestedKey)]", value)
  97. }
  98. } else if let array = value as? [AnyObject] {
  99. for value in array {
  100. components += queryComponents("\(key)[]", value)
  101. }
  102. } else {
  103. components.extend([(key, "\(value)")])
  104. }
  105. return components
  106. }
  107. }
  108. // MARK: -
  109. public protocol URLStringConvertible {
  110. var URLString: String { get }
  111. }
  112. extension String: URLStringConvertible {
  113. public var URLString: String {
  114. return self
  115. }
  116. }
  117. extension NSURL: URLStringConvertible {
  118. public var URLString: String {
  119. return self.absoluteString!
  120. }
  121. }
  122. extension NSURLComponents: URLStringConvertible {
  123. public var URLString: String {
  124. return self.URL!.URLString
  125. }
  126. }
  127. extension NSURLRequest: URLStringConvertible {
  128. public var URLString: String {
  129. return self.URL.URLString
  130. }
  131. }
  132. // MARK: -
  133. public protocol URLRequestConvertible {
  134. var URLRequest: NSURLRequest { get }
  135. }
  136. extension NSURLRequest: URLRequestConvertible {
  137. public var URLRequest: NSURLRequest {
  138. return self
  139. }
  140. }
  141. // MARK: -
  142. public class Manager {
  143. public class var sharedInstance: Manager {
  144. struct Singleton {
  145. static let instance = Manager()
  146. }
  147. return Singleton.instance
  148. }
  149. let delegate: SessionDelegate
  150. let session: NSURLSession!
  151. let operationQueue: NSOperationQueue = NSOperationQueue()
  152. var automaticallyStartsRequests: Bool = true
  153. public lazy var defaultHeaders: [String: String] = {
  154. // Accept-Encoding HTTP Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.3
  155. let acceptEncoding: String = "gzip;q=1.0,compress;q=0.5"
  156. // Accept-Language HTTP Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4
  157. let acceptLanguage: String = {
  158. var components: [String] = []
  159. for (index, languageCode) in enumerate(NSLocale.preferredLanguages() as [String]) {
  160. let q = 1.0 - (Double(index) * 0.1)
  161. components.append("\(languageCode);q=\(q)")
  162. if q <= 0.5 {
  163. break
  164. }
  165. }
  166. return join(",", components)
  167. }()
  168. // User-Agent Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.43
  169. let userAgent: String = {
  170. let info = NSBundle.mainBundle().infoDictionary
  171. let executable: AnyObject = info[kCFBundleExecutableKey] ?? "Unknown"
  172. let bundle: AnyObject = info[kCFBundleIdentifierKey] ?? "Unknown"
  173. let version: AnyObject = info[kCFBundleVersionKey] ?? "Unknown"
  174. let os: AnyObject = NSProcessInfo.processInfo().operatingSystemVersionString ?? "Unknown"
  175. var mutableUserAgent = NSMutableString(string: "\(executable)/\(bundle) (\(version); OS \(os))") as CFMutableString
  176. let transform = NSString(string: "Any-Latin; Latin-ASCII; [:^ASCII:] Remove") as CFString
  177. if CFStringTransform(mutableUserAgent, nil, transform, 0) == 1 {
  178. return mutableUserAgent as NSString
  179. }
  180. return "Alamofire"
  181. }()
  182. return ["Accept-Encoding": acceptEncoding,
  183. "Accept-Language": acceptLanguage,
  184. "User-Agent": userAgent]
  185. }()
  186. required public init(configuration: NSURLSessionConfiguration! = nil) {
  187. self.delegate = SessionDelegate()
  188. self.session = NSURLSession(configuration: configuration, delegate: self.delegate, delegateQueue: self.operationQueue)
  189. }
  190. deinit {
  191. self.session.invalidateAndCancel()
  192. }
  193. // MARK: -
  194. public func request(request: NSURLRequest) -> Request {
  195. var mutableRequest: NSMutableURLRequest! = request.mutableCopy() as NSMutableURLRequest
  196. for (field, value) in self.defaultHeaders {
  197. if mutableRequest.valueForHTTPHeaderField(field) == nil {
  198. mutableRequest.setValue(value, forHTTPHeaderField: field)
  199. }
  200. }
  201. var dataTask: NSURLSessionDataTask?
  202. dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
  203. dataTask = self.session.dataTaskWithRequest(mutableRequest)
  204. }
  205. let request = Request(session: self.session, task: dataTask!)
  206. self.delegate[request.delegate.task] = request.delegate
  207. request.resume()
  208. return request
  209. }
  210. class SessionDelegate: NSObject, NSURLSessionDelegate, NSURLSessionTaskDelegate, NSURLSessionDataDelegate, NSURLSessionDownloadDelegate {
  211. private var subdelegates: [Int: Request.TaskDelegate]
  212. private subscript(task: NSURLSessionTask) -> Request.TaskDelegate? {
  213. get {
  214. return self.subdelegates[task.taskIdentifier]
  215. }
  216. set(newValue) {
  217. self.subdelegates[task.taskIdentifier] = newValue
  218. }
  219. }
  220. var sessionDidBecomeInvalidWithError: ((NSURLSession!, NSError!) -> Void)?
  221. var sessionDidFinishEventsForBackgroundURLSession: ((NSURLSession!) -> Void)?
  222. var sessionDidReceiveChallenge: ((NSURLSession!, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential!))?
  223. var taskWillPerformHTTPRedirection: ((NSURLSession!, NSURLSessionTask!, NSHTTPURLResponse!, NSURLRequest!) -> (NSURLRequest!))?
  224. var taskDidReceiveChallenge: ((NSURLSession!, NSURLSessionTask!, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))?
  225. var taskDidSendBodyData: ((NSURLSession!, NSURLSessionTask!, Int64, Int64, Int64) -> Void)?
  226. var taskNeedNewBodyStream: ((NSURLSession!, NSURLSessionTask!) -> (NSInputStream!))?
  227. var dataTaskDidReceiveResponse: ((NSURLSession!, NSURLSessionDataTask!, NSURLResponse!) -> (NSURLSessionResponseDisposition))?
  228. var dataTaskDidBecomeDownloadTask: ((NSURLSession!, NSURLSessionDataTask!) -> Void)?
  229. var dataTaskDidReceiveData: ((NSURLSession!, NSURLSessionDataTask!, NSData!) -> Void)?
  230. var dataTaskWillCacheResponse: ((NSURLSession!, NSURLSessionDataTask!, NSCachedURLResponse!) -> (NSCachedURLResponse))?
  231. var downloadTaskDidFinishDownloadingToURL: ((NSURLSession!, NSURLSessionDownloadTask!, NSURL) -> (NSURL))?
  232. var downloadTaskDidWriteData: ((NSURLSession!, NSURLSessionDownloadTask!, Int64, Int64, Int64) -> Void)?
  233. var downloadTaskDidResumeAtOffset: ((NSURLSession!, NSURLSessionDownloadTask!, Int64, Int64) -> Void)?
  234. required override init() {
  235. self.subdelegates = Dictionary()
  236. super.init()
  237. }
  238. // MARK: NSURLSessionDelegate
  239. func URLSession(session: NSURLSession!, didBecomeInvalidWithError error: NSError!) {
  240. self.sessionDidBecomeInvalidWithError?(session, error)
  241. }
  242. func URLSession(session: NSURLSession!, didReceiveChallenge challenge: NSURLAuthenticationChallenge!, completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential!) -> Void)!) {
  243. if self.sessionDidReceiveChallenge != nil {
  244. completionHandler(self.sessionDidReceiveChallenge!(session, challenge))
  245. } else {
  246. completionHandler(.PerformDefaultHandling, nil)
  247. }
  248. }
  249. func URLSessionDidFinishEventsForBackgroundURLSession(session: NSURLSession!) {
  250. self.sessionDidFinishEventsForBackgroundURLSession?(session)
  251. }
  252. // MARK: NSURLSessionTaskDelegate
  253. func URLSession(session: NSURLSession!, task: NSURLSessionTask!, willPerformHTTPRedirection response: NSHTTPURLResponse!, newRequest request: NSURLRequest!, completionHandler: ((NSURLRequest!) -> Void)!) {
  254. var redirectRequest = request
  255. if self.taskWillPerformHTTPRedirection != nil {
  256. redirectRequest = self.taskWillPerformHTTPRedirection!(session, task, response, request)
  257. }
  258. completionHandler(redirectRequest)
  259. }
  260. func URLSession(session: NSURLSession!, task: NSURLSessionTask!, didReceiveChallenge challenge: NSURLAuthenticationChallenge!, completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential!) -> Void)!) {
  261. if let delegate = self[task] {
  262. delegate.URLSession(session, task: task, didReceiveChallenge: challenge, completionHandler: completionHandler)
  263. } else {
  264. self.URLSession(session, didReceiveChallenge: challenge, completionHandler: completionHandler)
  265. }
  266. }
  267. func URLSession(session: NSURLSession!, task: NSURLSessionTask!, needNewBodyStream completionHandler: ((NSInputStream!) -> Void)!) {
  268. if let delegate = self[task] {
  269. delegate.URLSession(session, task: task, needNewBodyStream: completionHandler)
  270. }
  271. }
  272. func URLSession(session: NSURLSession!, task: NSURLSessionTask!, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
  273. if let delegate = self[task] as? Request.UploadTaskDelegate {
  274. delegate.URLSession(session, task: task, didSendBodyData: bytesSent, totalBytesSent: totalBytesSent, totalBytesExpectedToSend: totalBytesExpectedToSend)
  275. }
  276. }
  277. func URLSession(session: NSURLSession!, task: NSURLSessionTask!, didCompleteWithError error: NSError!) {
  278. if let delegate = self[task] {
  279. delegate.URLSession(session, task: task, didCompleteWithError: error)
  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 self.dataTaskDidReceiveResponse != nil {
  286. disposition = self.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. self.dataTaskDidReceiveData?(session, dataTask, data)
  299. }
  300. func URLSession(session: NSURLSession!, dataTask: NSURLSessionDataTask!, willCacheResponse proposedResponse: NSCachedURLResponse!, completionHandler: ((NSCachedURLResponse!) -> Void)!) {
  301. var cachedResponse = proposedResponse
  302. if self.dataTaskWillCacheResponse != nil {
  303. cachedResponse = self.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. self.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. self.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. self.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 (self.sessionDidBecomeInvalidWithError != nil)
  331. case "URLSession:didReceiveChallenge:completionHandler:":
  332. return (self.sessionDidReceiveChallenge != nil)
  333. case "URLSessionDidFinishEventsForBackgroundURLSession:":
  334. return (self.sessionDidFinishEventsForBackgroundURLSession != nil)
  335. case "URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:":
  336. return (self.taskWillPerformHTTPRedirection != nil)
  337. case "URLSession:dataTask:didReceiveResponse:completionHandler:":
  338. return (self.dataTaskDidReceiveResponse != nil)
  339. case "URLSession:dataTask:willCacheResponse:completionHandler:":
  340. return (self.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. private var session: NSURLSession
  351. private var task: NSURLSessionTask { return self.delegate.task }
  352. public var request: NSURLRequest { return self.task.originalRequest }
  353. public var response: NSHTTPURLResponse? { return self.task.response as? NSHTTPURLResponse }
  354. public var progress: NSProgress? { return self.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(HTTPBasic user: String, password: String) -> Self {
  370. let credential = NSURLCredential(user: user, password: password, persistence: .ForSession)
  371. let protectionSpace = NSURLProtectionSpace(host: self.request.URL.host!, port: 0, `protocol`: self.request.URL.scheme, realm: nil, authenticationMethod: NSURLAuthenticationMethodHTTPBasic)
  372. return authenticate(usingCredential: credential, forProtectionSpace: protectionSpace)
  373. }
  374. public func authenticate(usingCredential credential: NSURLCredential, forProtectionSpace protectionSpace: NSURLProtectionSpace) -> Self {
  375. self.session.configuration.URLCredentialStorage?.setCredential(credential, forProtectionSpace: protectionSpace)
  376. return self
  377. }
  378. // MARK: Progress
  379. public func progress(closure: ((Int64, Int64, Int64) -> Void)? = nil) -> Self {
  380. if let uploadDelegate = self.delegate as? UploadTaskDelegate {
  381. uploadDelegate.uploadProgress = closure
  382. } else if let downloadDelegate = self.delegate as? DownloadTaskDelegate {
  383. downloadDelegate.downloadProgress = closure
  384. }
  385. return self
  386. }
  387. // MARK: Response
  388. public func response(completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Self {
  389. return response({ (request, response, data, error) in
  390. return (data, error)
  391. }, completionHandler: completionHandler)
  392. }
  393. public func response(priority: Int = DISPATCH_QUEUE_PRIORITY_DEFAULT, queue: dispatch_queue_t? = nil, serializer: (NSURLRequest, NSHTTPURLResponse?, NSData?, NSError?) -> (AnyObject?, NSError?), 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, nil)
  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 description = "\(self.request.HTTPMethod) \(self.request.URL)"
  650. if self.response != nil {
  651. description += " (\(self.response?.statusCode))"
  652. }
  653. return description
  654. }
  655. }
  656. extension Request: DebugPrintable {
  657. func cURLRepresentation() -> String {
  658. var components: [String] = ["$ curl -i"]
  659. let URL = self.request.URL
  660. if self.request.HTTPMethod != "GET" {
  661. components.append("-X \(self.request.HTTPMethod)")
  662. }
  663. if let credentialStorage = self.session.configuration.URLCredentialStorage {
  664. let protectionSpace = NSURLProtectionSpace(host: URL.host!, port: URL.port ?? 0, `protocol`: URL.scheme, realm: URL.host, authenticationMethod: NSURLAuthenticationMethodHTTPBasic)
  665. if let credentials = credentialStorage.credentialsForProtectionSpace(protectionSpace)?.values.array {
  666. if !credentials.isEmpty {
  667. if let credential = credentials[0] as? NSURLCredential {
  668. components.append("-u \(credential.user):\(credential.password)")
  669. }
  670. }
  671. }
  672. }
  673. if let cookieStorage = self.session.configuration.HTTPCookieStorage {
  674. if let cookies = cookieStorage.cookiesForURL(URL) as? [NSHTTPCookie] {
  675. if !cookies.isEmpty {
  676. let string = cookies.reduce(""){ $0 + "\($1.name)=\($1.value);" }
  677. components.append("-b \"\(string.substringToIndex(string.endIndex.predecessor()))\"")
  678. }
  679. }
  680. }
  681. for (field, value) in self.request.allHTTPHeaderFields! {
  682. switch field {
  683. case "Cookie":
  684. continue
  685. default:
  686. components.append("-H \"\(field): \(value)\"")
  687. }
  688. }
  689. if let HTTPBody = self.request.HTTPBody {
  690. components.append("-d \"\(NSString(data: HTTPBody, encoding: NSUTF8StringEncoding))\"")
  691. }
  692. // TODO: -T arguments for files
  693. components.append("\"\(URL.absoluteString!)\"")
  694. return join(" \\\n\t", components)
  695. }
  696. public var debugDescription: String {
  697. return self.cURLRepresentation()
  698. }
  699. }
  700. // MARK: - Response Serializers
  701. // MARK: String
  702. extension Request {
  703. public class func stringResponseSerializer(encoding: NSStringEncoding = NSUTF8StringEncoding) -> (NSURLRequest, NSHTTPURLResponse?, NSData?, NSError?) -> (AnyObject?, NSError?) {
  704. return { (_, _, data, error) in
  705. let string = NSString(data: data!, encoding: encoding)
  706. return (string, error)
  707. }
  708. }
  709. public func responseString(completionHandler: (NSURLRequest, NSHTTPURLResponse?, String?, NSError?) -> Void) -> Self {
  710. return responseString(completionHandler: completionHandler)
  711. }
  712. public func responseString(encoding: NSStringEncoding = NSUTF8StringEncoding, completionHandler: (NSURLRequest, NSHTTPURLResponse?, String?, NSError?) -> Void) -> Self {
  713. return response(serializer: Request.stringResponseSerializer(encoding: encoding), completionHandler: { request, response, string, error in
  714. completionHandler(request, response, string as? String, error)
  715. })
  716. }
  717. }
  718. // MARK: JSON
  719. extension Request {
  720. public class func JSONResponseSerializer(options: NSJSONReadingOptions = .AllowFragments) -> (NSURLRequest, NSHTTPURLResponse?, NSData?, NSError?) -> (AnyObject?, NSError?) {
  721. return { (request, response, data, error) in
  722. var serializationError: NSError?
  723. let JSON: AnyObject! = NSJSONSerialization.JSONObjectWithData(data!, options: options, error: &serializationError)
  724. return (JSON, serializationError)
  725. }
  726. }
  727. public func responseJSON(completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Self {
  728. return responseJSON(completionHandler: completionHandler)
  729. }
  730. public func responseJSON(options: NSJSONReadingOptions = .AllowFragments, completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Self {
  731. return response(serializer: Request.JSONResponseSerializer(options: options), completionHandler: { (request, response, JSON, error) in
  732. completionHandler(request, response, JSON, error)
  733. })
  734. }
  735. }
  736. // MARK: Property List
  737. extension Request {
  738. public class func propertyListResponseSerializer(options: NSPropertyListReadOptions = 0) -> (NSURLRequest, NSHTTPURLResponse?, NSData?, NSError?) -> (AnyObject?, NSError?) {
  739. return { (request, response, data, error) in
  740. var propertyListSerializationError: NSError?
  741. let plist: AnyObject! = NSPropertyListSerialization.propertyListWithData(data!, options: options, format: nil, error: &propertyListSerializationError)
  742. return (plist, propertyListSerializationError)
  743. }
  744. }
  745. public func responsePropertyList(completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Self {
  746. return responsePropertyList(completionHandler: completionHandler)
  747. }
  748. public func responsePropertyList(options: NSPropertyListReadOptions = 0, completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Self {
  749. return response(serializer: Request.propertyListResponseSerializer(options: options), completionHandler: { (request, response, plist, error) in
  750. completionHandler(request, response, plist, error)
  751. })
  752. }
  753. }
  754. // MARK: - Convenience
  755. private func URLRequest(method: Method, URLString: URLStringConvertible) -> NSURLRequest {
  756. let mutableURLRequest = NSMutableURLRequest(URL: NSURL(string: URLString.URLString))
  757. mutableURLRequest.HTTPMethod = method.toRaw()
  758. return mutableURLRequest
  759. }
  760. // MARK: Request
  761. public func request(method: Method, URLString: URLStringConvertible, parameters: [String: AnyObject]? = nil, encoding: ParameterEncoding = .URL) -> Request {
  762. return Manager.sharedInstance.request(encoding.encode(URLRequest(method, URLString), parameters: parameters).0)
  763. }
  764. // MARK: Upload
  765. public func upload(method: Method, URLString: URLStringConvertible, file: NSURL) -> Request {
  766. return Manager.sharedInstance.upload(URLRequest(method, URLString), file: file)
  767. }
  768. public func upload(method: Method, URLString: URLStringConvertible, data: NSData) -> Request {
  769. return Manager.sharedInstance.upload(URLRequest(method, URLString), data: data)
  770. }
  771. public func upload(method: Method, URLString: URLStringConvertible, stream: NSInputStream) -> Request {
  772. return Manager.sharedInstance.upload(URLRequest(method, URLString), stream: stream)
  773. }
  774. // MARK: Download
  775. public func download(method: Method, URLString: URLStringConvertible, destination: (NSURL, NSHTTPURLResponse) -> (NSURL)) -> Request {
  776. return Manager.sharedInstance.download(URLRequest(method, URLString), destination: destination)
  777. }
  778. public func download(resumeData data: NSData, destination: (NSURL, NSHTTPURLResponse) -> (NSURL)) -> Request {
  779. return Manager.sharedInstance.download(data, destination: destination)
  780. }