Alamofire.swift 42 KB

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