2
0

Alamofire.swift 63 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558
  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. /// Alamofire errors
  24. public let AlamofireErrorDomain = "com.alamofire.error"
  25. /**
  26. HTTP method definitions.
  27. See http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
  28. */
  29. public enum Method: String {
  30. case OPTIONS = "OPTIONS"
  31. case GET = "GET"
  32. case HEAD = "HEAD"
  33. case POST = "POST"
  34. case PUT = "PUT"
  35. case PATCH = "PATCH"
  36. case DELETE = "DELETE"
  37. case TRACE = "TRACE"
  38. case CONNECT = "CONNECT"
  39. }
  40. /**
  41. Used to specify the way in which a set of parameters are applied to a URL request.
  42. */
  43. public enum ParameterEncoding {
  44. /**
  45. A query string to be set as or appended to any existing URL query for `GET`, `HEAD`, and `DELETE` requests, or set as the body for requests with any other HTTP method. Since there is no published specification for how to encode collection types, the convention of appending `[]` to the key for array values (`foo[]=1&foo[]=2`), and appending the key surrounded by square brackets for nested dictionary values (`foo[bar]=baz`).
  46. */
  47. case URL
  48. /**
  49. Uses `NSJSONSerialization` to create a JSON representation of the parameters object, which is set as the body of the request.
  50. */
  51. case JSON
  52. /**
  53. Uses `NSPropertyListSerialization` to create a plist representation of the parameters object, according to the associated format and write options values, which is set as the body of the request.
  54. */
  55. case PropertyList(NSPropertyListFormat, NSPropertyListWriteOptions)
  56. /**
  57. Uses the associated closure value to construct a new request given an existing request and parameters.
  58. */
  59. case Custom((URLRequestConvertible, [String: AnyObject]?) -> (NSURLRequest, NSError?))
  60. /**
  61. Creates a URL request by encoding parameters and applying them onto an existing request.
  62. :param: URLRequest The request to have parameters applied
  63. :param: parameters The parameters to apply
  64. :returns: A tuple containing the constructed request and the error that occurred during parameter encoding, if any.
  65. */
  66. public func encode(URLRequest: URLRequestConvertible, parameters: [String: AnyObject]?) -> (NSURLRequest, NSError?) {
  67. if parameters == nil {
  68. return (URLRequest.URLRequest, nil)
  69. }
  70. var mutableURLRequest: NSMutableURLRequest! = URLRequest.URLRequest.mutableCopy() as NSMutableURLRequest
  71. var error: NSError? = nil
  72. switch self {
  73. case .URL:
  74. func query(parameters: [String: AnyObject]) -> String {
  75. var components: [(String, String)] = []
  76. for key in sorted(Array(parameters.keys), <) {
  77. let value: AnyObject! = parameters[key]
  78. components += queryComponents(key, value)
  79. }
  80. return join("&", components.map{"\($0)=\($1)"} as [String])
  81. }
  82. func encodesParametersInURL(method: Method) -> Bool {
  83. switch method {
  84. case .GET, .HEAD, .DELETE:
  85. return true
  86. default:
  87. return false
  88. }
  89. }
  90. let method = Method.fromRaw(mutableURLRequest.HTTPMethod)
  91. if method != nil && encodesParametersInURL(method!) {
  92. let URLComponents = NSURLComponents(URL: mutableURLRequest.URL!, resolvingAgainstBaseURL: false)
  93. URLComponents.query = (URLComponents.query != nil ? URLComponents.query! + "&" : "") + query(parameters!)
  94. mutableURLRequest.URL = URLComponents.URL
  95. } else {
  96. if mutableURLRequest.valueForHTTPHeaderField("Content-Type") == nil {
  97. mutableURLRequest.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
  98. }
  99. mutableURLRequest.HTTPBody = (CFURLCreateStringByAddingPercentEscapes(nil, query(parameters!) as NSString, nil, nil, CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding)) as NSString).dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
  100. }
  101. case .JSON:
  102. let options = NSJSONWritingOptions.allZeros
  103. if let data = NSJSONSerialization.dataWithJSONObject(parameters!, options: options, error: &error) {
  104. mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
  105. mutableURLRequest.HTTPBody = data
  106. }
  107. case .PropertyList(let (format, options)):
  108. if let data = NSPropertyListSerialization.dataWithPropertyList(parameters!, format: format, options: options, error: &error) {
  109. mutableURLRequest.setValue("application/x-plist", forHTTPHeaderField: "Content-Type")
  110. mutableURLRequest.HTTPBody = data
  111. }
  112. case .Custom(let closure):
  113. return closure(mutableURLRequest, parameters)
  114. }
  115. return (mutableURLRequest, error)
  116. }
  117. func queryComponents(key: String, _ value: AnyObject) -> [(String, String)] {
  118. var components: [(String, String)] = []
  119. if let dictionary = value as? [String: AnyObject] {
  120. for (nestedKey, value) in dictionary {
  121. components += queryComponents("\(key)[\(nestedKey)]", value)
  122. }
  123. } else if let array = value as? [AnyObject] {
  124. for value in array {
  125. components += queryComponents("\(key)[]", value)
  126. }
  127. } else {
  128. components.extend([(key, "\(value)")])
  129. }
  130. return components
  131. }
  132. }
  133. // MARK: - URLStringConvertible
  134. /**
  135. Types adopting the `URLStringConvertible` can be used to construct URL strings, which are then used to construct URL requests.
  136. */
  137. public protocol URLStringConvertible {
  138. /// The URL string.
  139. var URLString: String { get }
  140. }
  141. extension String: URLStringConvertible {
  142. public var URLString: String {
  143. return self
  144. }
  145. }
  146. extension NSURL: URLStringConvertible {
  147. public var URLString: String {
  148. return absoluteString!
  149. }
  150. }
  151. extension NSURLComponents: URLStringConvertible {
  152. public var URLString: String {
  153. return URL!.URLString
  154. }
  155. }
  156. extension NSURLRequest: URLStringConvertible {
  157. public var URLString: String {
  158. return URL.URLString
  159. }
  160. }
  161. // MARK: - URLRequestConvertible
  162. /**
  163. Types adopting the `URLRequestConvertible` can be used to construct URL requests.
  164. */
  165. public protocol URLRequestConvertible {
  166. /// The URL request.
  167. var URLRequest: NSURLRequest { get }
  168. }
  169. extension NSURLRequest: URLRequestConvertible {
  170. public var URLRequest: NSURLRequest {
  171. return self
  172. }
  173. }
  174. // MARK: -
  175. /**
  176. Responsible for creating and managing `Request` objects, as well as their underlying `NSURLSession`.
  177. */
  178. public class Manager {
  179. /**
  180. A shared instance of `Manager`, used by top-level Alamofire request methods, and suitable for use directly for any ad hoc requests.
  181. */
  182. public class var sharedInstance: Manager {
  183. struct Singleton {
  184. static var configuration: NSURLSessionConfiguration = {
  185. var configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
  186. configuration.HTTPAdditionalHeaders = {
  187. // Accept-Encoding HTTP Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.3
  188. let acceptEncoding: String = "gzip;q=1.0,compress;q=0.5"
  189. // Accept-Language HTTP Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4
  190. let acceptLanguage: String = {
  191. var components: [String] = []
  192. for (index, languageCode) in enumerate(NSLocale.preferredLanguages() as [String]) {
  193. let q = 1.0 - (Double(index) * 0.1)
  194. components.append("\(languageCode);q=\(q)")
  195. if q <= 0.5 {
  196. break
  197. }
  198. }
  199. return join(",", components)
  200. }()
  201. // User-Agent Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.43
  202. let userAgent: String = {
  203. let info = NSBundle.mainBundle().infoDictionary
  204. let executable: AnyObject = info[kCFBundleExecutableKey] ?? "Unknown"
  205. let bundle: AnyObject = info[kCFBundleIdentifierKey] ?? "Unknown"
  206. let version: AnyObject = info[kCFBundleVersionKey] ?? "Unknown"
  207. let os: AnyObject = NSProcessInfo.processInfo().operatingSystemVersionString ?? "Unknown"
  208. var mutableUserAgent = NSMutableString(string: "\(executable)/\(bundle) (\(version); OS \(os))") as CFMutableString
  209. let transform = NSString(string: "Any-Latin; Latin-ASCII; [:^ASCII:] Remove") as CFString
  210. if CFStringTransform(mutableUserAgent, nil, transform, 0) == 1 {
  211. return mutableUserAgent as NSString
  212. }
  213. return "Alamofire"
  214. }()
  215. return ["Accept-Encoding": acceptEncoding,
  216. "Accept-Language": acceptLanguage,
  217. "User-Agent": userAgent]
  218. }()
  219. return configuration
  220. }()
  221. static let instance = Manager(configuration: configuration)
  222. }
  223. return Singleton.instance
  224. }
  225. private let delegate: SessionDelegate
  226. let operationQueue: NSOperationQueue = NSOperationQueue()
  227. /// The underlying session.
  228. public let session: NSURLSession
  229. /// Whether to start requests immediately after being constructed. `true` by default.
  230. public var startRequestsImmediately: Bool = true
  231. /**
  232. :param: configuration The configuration used to construct the managed session.
  233. */
  234. required public init(configuration: NSURLSessionConfiguration? = nil) {
  235. self.delegate = SessionDelegate()
  236. self.session = NSURLSession(configuration: configuration, delegate: delegate, delegateQueue: operationQueue)
  237. }
  238. deinit {
  239. self.session.invalidateAndCancel()
  240. }
  241. // MARK: -
  242. /**
  243. Creates a request for the specified URL request.
  244. If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
  245. :param: URLRequest The URL request
  246. :returns: The created request.
  247. */
  248. public func request(URLRequest: URLRequestConvertible) -> Request {
  249. var dataTask: NSURLSessionDataTask?
  250. dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
  251. dataTask = self.session.dataTaskWithRequest(URLRequest.URLRequest)
  252. }
  253. let request = Request(session: session, task: dataTask!)
  254. delegate[request.delegate.task] = request.delegate
  255. if startRequestsImmediately {
  256. request.resume()
  257. }
  258. return request
  259. }
  260. class SessionDelegate: NSObject, NSURLSessionDelegate, NSURLSessionTaskDelegate, NSURLSessionDataDelegate, NSURLSessionDownloadDelegate {
  261. private var subdelegates: [Int: Request.TaskDelegate]
  262. private subscript(task: NSURLSessionTask) -> Request.TaskDelegate? {
  263. get {
  264. return subdelegates[task.taskIdentifier]
  265. }
  266. set {
  267. subdelegates[task.taskIdentifier] = newValue
  268. }
  269. }
  270. var sessionDidBecomeInvalidWithError: ((NSURLSession!, NSError!) -> Void)?
  271. var sessionDidFinishEventsForBackgroundURLSession: ((NSURLSession!) -> Void)?
  272. var sessionDidReceiveChallenge: ((NSURLSession!, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential!))?
  273. var taskWillPerformHTTPRedirection: ((NSURLSession!, NSURLSessionTask!, NSHTTPURLResponse!, NSURLRequest!) -> (NSURLRequest!))?
  274. var taskDidReceiveChallenge: ((NSURLSession!, NSURLSessionTask!, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))?
  275. var taskDidSendBodyData: ((NSURLSession!, NSURLSessionTask!, Int64, Int64, Int64) -> Void)?
  276. var taskNeedNewBodyStream: ((NSURLSession!, NSURLSessionTask!) -> (NSInputStream!))?
  277. var dataTaskDidReceiveResponse: ((NSURLSession!, NSURLSessionDataTask!, NSURLResponse!) -> (NSURLSessionResponseDisposition))?
  278. var dataTaskDidBecomeDownloadTask: ((NSURLSession!, NSURLSessionDataTask!) -> Void)?
  279. var dataTaskDidReceiveData: ((NSURLSession!, NSURLSessionDataTask!, NSData!) -> Void)?
  280. var dataTaskWillCacheResponse: ((NSURLSession!, NSURLSessionDataTask!, NSCachedURLResponse!) -> (NSCachedURLResponse))?
  281. var downloadTaskDidFinishDownloadingToURL: ((NSURLSession!, NSURLSessionDownloadTask!, NSURL) -> (NSURL))?
  282. var downloadTaskDidWriteData: ((NSURLSession!, NSURLSessionDownloadTask!, Int64, Int64, Int64) -> Void)?
  283. var downloadTaskDidResumeAtOffset: ((NSURLSession!, NSURLSessionDownloadTask!, Int64, Int64) -> Void)?
  284. required override init() {
  285. self.subdelegates = Dictionary()
  286. super.init()
  287. }
  288. // MARK: NSURLSessionDelegate
  289. func URLSession(session: NSURLSession!, didBecomeInvalidWithError error: NSError!) {
  290. sessionDidBecomeInvalidWithError?(session, error)
  291. }
  292. func URLSession(session: NSURLSession!, didReceiveChallenge challenge: NSURLAuthenticationChallenge!, completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential!) -> Void)!) {
  293. if sessionDidReceiveChallenge != nil {
  294. completionHandler(sessionDidReceiveChallenge!(session, challenge))
  295. } else {
  296. completionHandler(.PerformDefaultHandling, nil)
  297. }
  298. }
  299. func URLSessionDidFinishEventsForBackgroundURLSession(session: NSURLSession!) {
  300. sessionDidFinishEventsForBackgroundURLSession?(session)
  301. }
  302. // MARK: NSURLSessionTaskDelegate
  303. func URLSession(session: NSURLSession!, task: NSURLSessionTask!, willPerformHTTPRedirection response: NSHTTPURLResponse!, newRequest request: NSURLRequest!, completionHandler: ((NSURLRequest!) -> Void)!) {
  304. var redirectRequest = request
  305. if taskWillPerformHTTPRedirection != nil {
  306. redirectRequest = taskWillPerformHTTPRedirection!(session, task, response, request)
  307. }
  308. completionHandler(redirectRequest)
  309. }
  310. func URLSession(session: NSURLSession!, task: NSURLSessionTask!, didReceiveChallenge challenge: NSURLAuthenticationChallenge!, completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential!) -> Void)!) {
  311. if let delegate = self[task] {
  312. delegate.URLSession(session, task: task, didReceiveChallenge: challenge, completionHandler: completionHandler)
  313. } else {
  314. URLSession(session, didReceiveChallenge: challenge, completionHandler: completionHandler)
  315. }
  316. }
  317. func URLSession(session: NSURLSession!, task: NSURLSessionTask!, needNewBodyStream completionHandler: ((NSInputStream!) -> Void)!) {
  318. if let delegate = self[task] {
  319. delegate.URLSession(session, task: task, needNewBodyStream: completionHandler)
  320. }
  321. }
  322. func URLSession(session: NSURLSession!, task: NSURLSessionTask!, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
  323. if let delegate = self[task] as? Request.UploadTaskDelegate {
  324. delegate.URLSession(session, task: task, didSendBodyData: bytesSent, totalBytesSent: totalBytesSent, totalBytesExpectedToSend: totalBytesExpectedToSend)
  325. }
  326. }
  327. func URLSession(session: NSURLSession!, task: NSURLSessionTask!, didCompleteWithError error: NSError!) {
  328. if let delegate = self[task] {
  329. delegate.URLSession(session, task: task, didCompleteWithError: error)
  330. self[task] = nil
  331. }
  332. }
  333. // MARK: NSURLSessionDataDelegate
  334. func URLSession(session: NSURLSession!, dataTask: NSURLSessionDataTask!, didReceiveResponse response: NSURLResponse!, completionHandler: ((NSURLSessionResponseDisposition) -> Void)!) {
  335. var disposition: NSURLSessionResponseDisposition = .Allow
  336. if dataTaskDidReceiveResponse != nil {
  337. disposition = dataTaskDidReceiveResponse!(session, dataTask, response)
  338. }
  339. completionHandler(disposition)
  340. }
  341. func URLSession(session: NSURLSession!, dataTask: NSURLSessionDataTask!, didBecomeDownloadTask downloadTask: NSURLSessionDownloadTask!) {
  342. let downloadDelegate = Request.DownloadTaskDelegate(task: downloadTask)
  343. self[downloadTask] = downloadDelegate
  344. }
  345. func URLSession(session: NSURLSession!, dataTask: NSURLSessionDataTask!, didReceiveData data: NSData!) {
  346. if let delegate = self[dataTask] as? Request.DataTaskDelegate {
  347. delegate.URLSession(session, dataTask: dataTask, didReceiveData: data)
  348. }
  349. dataTaskDidReceiveData?(session, dataTask, data)
  350. }
  351. func URLSession(session: NSURLSession!, dataTask: NSURLSessionDataTask!, willCacheResponse proposedResponse: NSCachedURLResponse!, completionHandler: ((NSCachedURLResponse!) -> Void)!) {
  352. var cachedResponse = proposedResponse
  353. if dataTaskWillCacheResponse != nil {
  354. cachedResponse = dataTaskWillCacheResponse!(session, dataTask, proposedResponse)
  355. }
  356. completionHandler(cachedResponse)
  357. }
  358. // MARK: NSURLSessionDownloadDelegate
  359. func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL) {
  360. if let delegate = self[downloadTask] as? Request.DownloadTaskDelegate {
  361. delegate.URLSession(session, downloadTask: downloadTask, didFinishDownloadingToURL: location)
  362. }
  363. downloadTaskDidFinishDownloadingToURL?(session, downloadTask, location)
  364. }
  365. func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
  366. if let delegate = self[downloadTask] as? Request.DownloadTaskDelegate {
  367. delegate.URLSession(session, downloadTask: downloadTask, didWriteData: bytesWritten, totalBytesWritten: totalBytesWritten, totalBytesExpectedToWrite: totalBytesExpectedToWrite)
  368. }
  369. downloadTaskDidWriteData?(session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite)
  370. }
  371. func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64) {
  372. if let delegate = self[downloadTask] as? Request.DownloadTaskDelegate {
  373. delegate.URLSession(session, downloadTask: downloadTask, didResumeAtOffset: fileOffset, expectedTotalBytes: expectedTotalBytes)
  374. }
  375. downloadTaskDidResumeAtOffset?(session, downloadTask, fileOffset, expectedTotalBytes)
  376. }
  377. // MARK: NSObject
  378. override func respondsToSelector(selector: Selector) -> Bool {
  379. switch selector {
  380. case "URLSession:didBecomeInvalidWithError:":
  381. return (sessionDidBecomeInvalidWithError != nil)
  382. case "URLSession:didReceiveChallenge:completionHandler:":
  383. return (sessionDidReceiveChallenge != nil)
  384. case "URLSessionDidFinishEventsForBackgroundURLSession:":
  385. return (sessionDidFinishEventsForBackgroundURLSession != nil)
  386. case "URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:":
  387. return (taskWillPerformHTTPRedirection != nil)
  388. case "URLSession:dataTask:didReceiveResponse:completionHandler:":
  389. return (dataTaskDidReceiveResponse != nil)
  390. case "URLSession:dataTask:willCacheResponse:completionHandler:":
  391. return (dataTaskWillCacheResponse != nil)
  392. default:
  393. return self.dynamicType.instancesRespondToSelector(selector)
  394. }
  395. }
  396. }
  397. }
  398. // MARK: -
  399. /**
  400. Responsible for sending a request and receiving the response and associated data from the server, as well as managing its underlying `NSURLSessionTask`.
  401. */
  402. public class Request {
  403. private let delegate: TaskDelegate
  404. /// The underlying task.
  405. public var task: NSURLSessionTask { return delegate.task }
  406. /// The session belonging to the underlying task.
  407. public let session: NSURLSession
  408. /// The request sent or to be sent to the server.
  409. public var request: NSURLRequest { return task.originalRequest }
  410. /// The response received from the server, if any.
  411. public var response: NSHTTPURLResponse? { return task.response as? NSHTTPURLResponse }
  412. /// The progress of the request lifecycle.
  413. public var progress: NSProgress? { return delegate.progress }
  414. private init(session: NSURLSession, task: NSURLSessionTask) {
  415. self.session = session
  416. switch task {
  417. case is NSURLSessionUploadTask:
  418. self.delegate = UploadTaskDelegate(task: task)
  419. case is NSURLSessionDataTask:
  420. self.delegate = DataTaskDelegate(task: task)
  421. case is NSURLSessionDownloadTask:
  422. self.delegate = DownloadTaskDelegate(task: task)
  423. default:
  424. self.delegate = TaskDelegate(task: task)
  425. }
  426. }
  427. // MARK: Authentication
  428. /**
  429. Associates an HTTP Basic credential with the request.
  430. :param: user The user.
  431. :param: password The password.
  432. :returns: The request.
  433. */
  434. public func authenticate(#user: String, password: String) -> Self {
  435. let credential = NSURLCredential(user: user, password: password, persistence: .ForSession)
  436. return authenticate(usingCredential: credential)
  437. }
  438. /**
  439. Associates a specified credential with the request.
  440. :param: credential The credential.
  441. :returns: The request.
  442. */
  443. public func authenticate(usingCredential credential: NSURLCredential) -> Self {
  444. delegate.credential = credential
  445. return self
  446. }
  447. // MARK: Progress
  448. /**
  449. Sets a closure to be called periodically during the lifecycle of the request as data is written to or read from the server.
  450. - For uploads, the progress closure returns the bytes written, total bytes written, and total bytes expected to write.
  451. - For downloads, the progress closure returns the bytes read, total bytes read, and total bytes expected to write.
  452. :param: closure The code to be executed periodically during the lifecycle of the request.
  453. :returns: The request.
  454. */
  455. public func progress(closure: ((Int64, Int64, Int64) -> Void)? = nil) -> Self {
  456. if let uploadDelegate = delegate as? UploadTaskDelegate {
  457. uploadDelegate.uploadProgress = closure
  458. } else if let dataDelegate = delegate as? DataTaskDelegate {
  459. dataDelegate.dataProgress = closure
  460. } else if let downloadDelegate = delegate as? DownloadTaskDelegate {
  461. downloadDelegate.downloadProgress = closure
  462. }
  463. return self
  464. }
  465. // MARK: Response
  466. /**
  467. A closure used by response handlers that takes a request, response, and data and returns a serialized object and any error that occured in the process.
  468. */
  469. public typealias Serializer = (NSURLRequest, NSHTTPURLResponse?, NSData?) -> (AnyObject?, NSError?)
  470. /**
  471. Creates a response serializer that returns the associated data as-is.
  472. :returns: A data response serializer.
  473. */
  474. public class func responseDataSerializer() -> Serializer {
  475. return { (request, response, data) in
  476. return (data, nil)
  477. }
  478. }
  479. /**
  480. Adds a handler to be called once the request has finished.
  481. :param: completionHandler The code to be executed once the request has finished.
  482. :returns: The request.
  483. */
  484. public func response(completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Self {
  485. return response(Request.responseDataSerializer(), completionHandler: completionHandler)
  486. }
  487. /**
  488. Adds a handler to be called once the request has finished.
  489. :param: priority The dispatch priority / quality of service used to process the response handler. `DISPATCH_QUEUE_PRIORITY_DEFAULT` by default.
  490. :param: queue The queue on which the completion handler is dispatched.
  491. :param: serializer The closure responsible for serializing the request, response, and data.
  492. :param: completionHandler The code to be executed once the request has finished.
  493. :returns: The request.
  494. */
  495. public func response(priority: Int = DISPATCH_QUEUE_PRIORITY_DEFAULT, queue: dispatch_queue_t? = nil, serializer: Serializer, completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Self {
  496. dispatch_sync(delegate.queue, {
  497. dispatch_sync(dispatch_get_global_queue(priority, 0), {
  498. let (responseObject: AnyObject?, serializationError: NSError?) = serializer(self.request, self.response, self.delegate.data)
  499. dispatch_async(queue ?? dispatch_get_main_queue(), {
  500. completionHandler(self.request, self.response, responseObject, self.delegate.error ?? serializationError)
  501. })
  502. })
  503. })
  504. return self
  505. }
  506. /**
  507. Suspends the request.
  508. */
  509. public func suspend() {
  510. task.suspend()
  511. }
  512. /**
  513. Resumes the request.
  514. */
  515. public func resume() {
  516. task.resume()
  517. }
  518. /**
  519. Cancels the request.
  520. */
  521. public func cancel() {
  522. if let downloadDelegate = delegate as? DownloadTaskDelegate {
  523. downloadDelegate.downloadTask.cancelByProducingResumeData { (data) in
  524. downloadDelegate.resumeData = data
  525. }
  526. } else {
  527. task.cancel()
  528. }
  529. }
  530. class TaskDelegate: NSObject, NSURLSessionTaskDelegate {
  531. let task: NSURLSessionTask
  532. let queue: dispatch_queue_t
  533. let progress: NSProgress
  534. var data: NSData? { return nil }
  535. private(set) var error: NSError?
  536. var credential: NSURLCredential?
  537. var taskWillPerformHTTPRedirection: ((NSURLSession!, NSURLSessionTask!, NSHTTPURLResponse!, NSURLRequest!) -> (NSURLRequest!))?
  538. var taskDidReceiveChallenge: ((NSURLSession!, NSURLSessionTask!, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))?
  539. var taskDidSendBodyData: ((NSURLSession!, NSURLSessionTask!, Int64, Int64, Int64) -> Void)?
  540. var taskNeedNewBodyStream: ((NSURLSession!, NSURLSessionTask!) -> (NSInputStream!))?
  541. init(task: NSURLSessionTask) {
  542. self.task = task
  543. self.progress = NSProgress(totalUnitCount: 0)
  544. let label: String = "com.alamofire.task-\(task.taskIdentifier)"
  545. let queue = dispatch_queue_create((label as NSString).UTF8String, DISPATCH_QUEUE_SERIAL)
  546. dispatch_suspend(queue)
  547. self.queue = queue
  548. }
  549. // MARK: NSURLSessionTaskDelegate
  550. func URLSession(session: NSURLSession!, task: NSURLSessionTask!, willPerformHTTPRedirection response: NSHTTPURLResponse!, newRequest request: NSURLRequest!, completionHandler: ((NSURLRequest!) -> Void)!) {
  551. var redirectRequest = request
  552. if taskWillPerformHTTPRedirection != nil {
  553. redirectRequest = taskWillPerformHTTPRedirection!(session, task, response, request)
  554. }
  555. completionHandler(redirectRequest)
  556. }
  557. func URLSession(session: NSURLSession!, task: NSURLSessionTask!, didReceiveChallenge challenge: NSURLAuthenticationChallenge!, completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential!) -> Void)!) {
  558. var disposition: NSURLSessionAuthChallengeDisposition = .PerformDefaultHandling
  559. var credential: NSURLCredential?
  560. if taskDidReceiveChallenge != nil {
  561. (disposition, credential) = taskDidReceiveChallenge!(session, task, challenge)
  562. } else {
  563. if challenge.previousFailureCount > 0 {
  564. disposition = .CancelAuthenticationChallenge
  565. } else {
  566. // TODO: Incorporate Trust Evaluation & TLS Chain Validation
  567. switch challenge.protectionSpace.authenticationMethod! {
  568. case NSURLAuthenticationMethodServerTrust:
  569. credential = NSURLCredential(forTrust: challenge.protectionSpace.serverTrust)
  570. default:
  571. credential = self.credential ?? session.configuration.URLCredentialStorage?.defaultCredentialForProtectionSpace(challenge.protectionSpace)
  572. }
  573. if credential != nil {
  574. disposition = .UseCredential
  575. }
  576. }
  577. }
  578. completionHandler(disposition, credential)
  579. }
  580. func URLSession(session: NSURLSession!, task: NSURLSessionTask!, needNewBodyStream completionHandler: ((NSInputStream!) -> Void)!) {
  581. var bodyStream: NSInputStream?
  582. if taskNeedNewBodyStream != nil {
  583. bodyStream = taskNeedNewBodyStream!(session, task)
  584. }
  585. completionHandler(bodyStream)
  586. }
  587. func URLSession(session: NSURLSession!, task: NSURLSessionTask!, didCompleteWithError error: NSError!) {
  588. if error != nil {
  589. self.error = error
  590. }
  591. dispatch_resume(queue)
  592. }
  593. }
  594. class DataTaskDelegate: TaskDelegate, NSURLSessionDataDelegate {
  595. var dataTask: NSURLSessionDataTask! { return task as NSURLSessionDataTask }
  596. private var mutableData: NSMutableData
  597. override var data: NSData? {
  598. return mutableData
  599. }
  600. private var expectedContentLength: Int64?
  601. var dataTaskDidReceiveResponse: ((NSURLSession!, NSURLSessionDataTask!, NSURLResponse!) -> (NSURLSessionResponseDisposition))?
  602. var dataTaskDidBecomeDownloadTask: ((NSURLSession!, NSURLSessionDataTask!) -> Void)?
  603. var dataTaskDidReceiveData: ((NSURLSession!, NSURLSessionDataTask!, NSData!) -> Void)?
  604. var dataTaskWillCacheResponse: ((NSURLSession!, NSURLSessionDataTask!, NSCachedURLResponse!) -> (NSCachedURLResponse))?
  605. var dataProgress: ((bytesReceived: Int64, totalBytesReceived: Int64, totalBytesExpectedToReceive: Int64) -> Void)?
  606. override init(task: NSURLSessionTask) {
  607. self.mutableData = NSMutableData()
  608. super.init(task: task)
  609. }
  610. // MARK: NSURLSessionDataDelegate
  611. func URLSession(session: NSURLSession!, dataTask: NSURLSessionDataTask!, didReceiveResponse response: NSURLResponse!, completionHandler: ((NSURLSessionResponseDisposition) -> Void)!) {
  612. var disposition: NSURLSessionResponseDisposition = .Allow
  613. expectedContentLength = response.expectedContentLength
  614. if dataTaskDidReceiveResponse != nil {
  615. disposition = dataTaskDidReceiveResponse!(session, dataTask, response)
  616. }
  617. completionHandler(disposition)
  618. }
  619. func URLSession(session: NSURLSession!, dataTask: NSURLSessionDataTask!, didBecomeDownloadTask downloadTask: NSURLSessionDownloadTask!) {
  620. dataTaskDidBecomeDownloadTask?(session, dataTask)
  621. }
  622. func URLSession(session: NSURLSession!, dataTask: NSURLSessionDataTask!, didReceiveData data: NSData!) {
  623. dataTaskDidReceiveData?(session, dataTask, data)
  624. mutableData.appendData(data)
  625. if let expectedContentLength = dataTask?.response?.expectedContentLength {
  626. dataProgress?(bytesReceived: Int64(data.length), totalBytesReceived: Int64(mutableData.length), totalBytesExpectedToReceive: expectedContentLength)
  627. }
  628. }
  629. func URLSession(session: NSURLSession!, dataTask: NSURLSessionDataTask!, willCacheResponse proposedResponse: NSCachedURLResponse!, completionHandler: ((NSCachedURLResponse!) -> Void)!) {
  630. var cachedResponse = proposedResponse
  631. if dataTaskWillCacheResponse != nil {
  632. cachedResponse = dataTaskWillCacheResponse!(session, dataTask, proposedResponse)
  633. }
  634. completionHandler(cachedResponse)
  635. }
  636. }
  637. }
  638. // MARK: - Validation
  639. extension Request {
  640. /**
  641. A closure used to validate a request that takes a URL request and URL response, and returns whether the request was valid.
  642. */
  643. public typealias Validation = (NSURLRequest, NSHTTPURLResponse) -> (Bool)
  644. /**
  645. Validates the request, using the specified closure.
  646. If validation fails, subsequent calls to response handlers will have an associated error.
  647. :param: validation A closure to validate the request.
  648. :returns: The request.
  649. */
  650. public func validate(validation: Validation) -> Self {
  651. return response(priority: DISPATCH_QUEUE_PRIORITY_HIGH, queue: self.delegate.queue, serializer: Request.responseDataSerializer()){ (request, response, data, error) in
  652. if response != nil && error == nil {
  653. if !validation(request, response!) {
  654. self.delegate.error = NSError(domain: AlamofireErrorDomain, code: -1, userInfo: nil)
  655. }
  656. }
  657. }
  658. }
  659. // MARK: Status Code
  660. private class func response(response: NSHTTPURLResponse, hasAcceptableStatusCode statusCodes: [Int]) -> Bool {
  661. return contains(statusCodes, response.statusCode)
  662. }
  663. /**
  664. Validates that the response has a status code in the specified range.
  665. If validation fails, subsequent calls to response handlers will have an associated error.
  666. :param: range The range of acceptable status codes.
  667. :returns: The request.
  668. */
  669. public func validate(statusCode range: Range<Int>) -> Self {
  670. return validate { (_, response) in
  671. return Request.response(response, hasAcceptableStatusCode: range.map({$0}))
  672. }
  673. }
  674. /**
  675. Validates that the response has a status code in the specified array.
  676. If validation fails, subsequent calls to response handlers will have an associated error.
  677. :param: array The acceptable status codes.
  678. :returns: The request.
  679. */
  680. public func validate(statusCode array: [Int]) -> Self {
  681. return validate { (_, response) in
  682. return Request.response(response, hasAcceptableStatusCode: array)
  683. }
  684. }
  685. // MARK: Content-Type
  686. private struct MIMEType {
  687. let type: String
  688. let subtype: String
  689. init(_ string: String) {
  690. let components = string.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).substringToIndex(string.rangeOfString(";")?.endIndex ?? string.endIndex).componentsSeparatedByString("/")
  691. self.type = components.first!
  692. self.subtype = components.last!
  693. }
  694. func matches(MIME: MIMEType) -> Bool {
  695. switch (type, subtype) {
  696. case ("*", "*"), ("*", MIME.subtype), (MIME.type, "*"), (MIME.type, MIME.subtype):
  697. return true
  698. default:
  699. return false
  700. }
  701. }
  702. }
  703. private class func response(response: NSHTTPURLResponse, hasAcceptableContentType contentTypes: [String]) -> Bool {
  704. if response.MIMEType != nil {
  705. let responseMIMEType = MIMEType(response.MIMEType!)
  706. for acceptableMIMEType in contentTypes.map({MIMEType($0)}) {
  707. if acceptableMIMEType.matches(responseMIMEType) {
  708. return true
  709. }
  710. }
  711. }
  712. return false
  713. }
  714. /**
  715. Validates that the response has a content type in the specified array.
  716. If validation fails, subsequent calls to response handlers will have an associated error.
  717. :param: contentType The acceptable content types, which may specify wildcard types and/or subtypes.
  718. :returns: The request.
  719. */
  720. public func validate(contentType array: [String]) -> Self {
  721. return validate {(_, response) in
  722. return Request.response(response, hasAcceptableContentType: array)
  723. }
  724. }
  725. // MARK: Automatic
  726. /**
  727. Validates that the response has a status code in the default acceptable range of 200...299, and that the content type matches any specified in the Accept HTTP header field.
  728. If validation fails, subsequent calls to response handlers will have an associated error.
  729. :returns: The request.
  730. */
  731. public func validate() -> Self {
  732. let acceptableStatusCodes: Range<Int> = 200..<300
  733. let acceptableContentTypes: [String] = {
  734. if let accept = self.request.valueForHTTPHeaderField("Accept") {
  735. return accept.componentsSeparatedByString(",")
  736. }
  737. return ["*/*"]
  738. }()
  739. return validate(statusCode: acceptableStatusCodes).validate(contentType: acceptableContentTypes)
  740. }
  741. }
  742. // MARK: - Upload
  743. extension Manager {
  744. private enum Uploadable {
  745. case Data(NSURLRequest, NSData)
  746. case File(NSURLRequest, NSURL)
  747. case Stream(NSURLRequest, NSInputStream)
  748. }
  749. private func upload(uploadable: Uploadable) -> Request {
  750. var uploadTask: NSURLSessionUploadTask!
  751. var stream: NSInputStream?
  752. switch uploadable {
  753. case .Data(let request, let data):
  754. uploadTask = session.uploadTaskWithRequest(request, fromData: data)
  755. case .File(let request, let fileURL):
  756. uploadTask = session.uploadTaskWithRequest(request, fromFile: fileURL)
  757. case .Stream(let request, var stream):
  758. uploadTask = session.uploadTaskWithStreamedRequest(request)
  759. }
  760. let request = Request(session: session, task: uploadTask)
  761. if stream != nil {
  762. request.delegate.taskNeedNewBodyStream = { _, _ in
  763. return stream
  764. }
  765. }
  766. delegate[request.delegate.task] = request.delegate
  767. if startRequestsImmediately {
  768. request.resume()
  769. }
  770. return request
  771. }
  772. // MARK: File
  773. /**
  774. Creates a request for uploading a file to the specified URL request.
  775. If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
  776. :param: URLRequest The URL request
  777. :param: file The file to upload
  778. :returns: The created upload request.
  779. */
  780. public func upload(URLRequest: URLRequestConvertible, file: NSURL) -> Request {
  781. return upload(.File(URLRequest.URLRequest, file))
  782. }
  783. // MARK: Data
  784. /**
  785. Creates a request for uploading data to the specified URL request.
  786. If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
  787. :param: URLRequest The URL request
  788. :param: data The data to upload
  789. :returns: The created upload request.
  790. */
  791. public func upload(URLRequest: URLRequestConvertible, data: NSData) -> Request {
  792. return upload(.Data(URLRequest.URLRequest, data))
  793. }
  794. // MARK: Stream
  795. /**
  796. Creates a request for uploading a stream to the specified URL request.
  797. If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
  798. :param: URLRequest The URL request
  799. :param: stream The stream to upload
  800. :returns: The created upload request.
  801. */
  802. public func upload(URLRequest: URLRequestConvertible, stream: NSInputStream) -> Request {
  803. return upload(.Stream(URLRequest.URLRequest, stream))
  804. }
  805. }
  806. extension Request {
  807. class UploadTaskDelegate: DataTaskDelegate {
  808. var uploadTask: NSURLSessionUploadTask! { return task as NSURLSessionUploadTask }
  809. var uploadProgress: ((Int64, Int64, Int64) -> Void)!
  810. // MARK: NSURLSessionTaskDelegate
  811. func URLSession(session: NSURLSession!, task: NSURLSessionTask!, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
  812. if uploadProgress != nil {
  813. uploadProgress(bytesSent, totalBytesSent, totalBytesExpectedToSend)
  814. }
  815. progress.totalUnitCount = totalBytesExpectedToSend
  816. progress.completedUnitCount = totalBytesSent
  817. }
  818. }
  819. }
  820. // MARK: - Download
  821. extension Manager {
  822. private enum Downloadable {
  823. case Request(NSURLRequest)
  824. case ResumeData(NSData)
  825. }
  826. private func download(downloadable: Downloadable, destination: (NSURL, NSHTTPURLResponse) -> (NSURL)) -> Request {
  827. var downloadTask: NSURLSessionDownloadTask!
  828. switch downloadable {
  829. case .Request(let request):
  830. downloadTask = session.downloadTaskWithRequest(request)
  831. case .ResumeData(let resumeData):
  832. downloadTask = session.downloadTaskWithResumeData(resumeData)
  833. }
  834. let request = Request(session: session, task: downloadTask)
  835. if let downloadDelegate = request.delegate as? Request.DownloadTaskDelegate {
  836. downloadDelegate.downloadTaskDidFinishDownloadingToURL = { (session, downloadTask, URL) in
  837. return destination(URL, downloadTask.response as NSHTTPURLResponse)
  838. }
  839. }
  840. delegate[request.delegate.task] = request.delegate
  841. if startRequestsImmediately {
  842. request.resume()
  843. }
  844. return request
  845. }
  846. // MARK: Request
  847. /**
  848. Creates a request for downloading from the specified URL request.
  849. If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
  850. :param: URLRequest The URL request
  851. :param: destination The closure used to determine the destination of the downloaded file.
  852. :returns: The created download request.
  853. */
  854. public func download(URLRequest: URLRequestConvertible, destination: (NSURL, NSHTTPURLResponse) -> (NSURL)) -> Request {
  855. return download(.Request(URLRequest.URLRequest), destination: destination)
  856. }
  857. // MARK: Resume Data
  858. /**
  859. Creates a request for downloading from the resume data produced from a previous request cancellation.
  860. If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
  861. :param: resumeData The resume data. This is an opaque data blob produced by `NSURLSessionDownloadTask` when a task is cancelled. See `NSURLSession -downloadTaskWithResumeData:` for additional information.
  862. :param: destination The closure used to determine the destination of the downloaded file.
  863. :returns: The created download request.
  864. */
  865. public func download(resumeData: NSData, destination: Request.DownloadFileDestination) -> Request {
  866. return download(.ResumeData(resumeData), destination: destination)
  867. }
  868. }
  869. extension Request {
  870. /**
  871. A closure executed once a request has successfully completed in order to determine where to move the temporary file written to during the download process. The closure takes two arguments: the temporary file URL and the URL response, and returns a single argument: the file URL where the temporary file should be moved.
  872. */
  873. public typealias DownloadFileDestination = (NSURL, NSHTTPURLResponse) -> (NSURL)
  874. /**
  875. Creates a download file destination closure which uses the default file manager to move the temporary file to a file URL in the first available directory with the specified search path directory and search path domain mask.
  876. :param: directory The search path directory. `.DocumentDirectory` by default.
  877. :param: domain The search path domain mask. `.UserDomainMask` by default.
  878. :returns: A download file destination closure.
  879. */
  880. public class func suggestedDownloadDestination(directory: NSSearchPathDirectory = .DocumentDirectory, domain: NSSearchPathDomainMask = .UserDomainMask) -> DownloadFileDestination {
  881. return { (temporaryURL, response) -> (NSURL) in
  882. if let directoryURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0] as? NSURL {
  883. return directoryURL.URLByAppendingPathComponent(response.suggestedFilename!)
  884. }
  885. return temporaryURL
  886. }
  887. }
  888. class DownloadTaskDelegate: TaskDelegate, NSURLSessionDownloadDelegate {
  889. var downloadTask: NSURLSessionDownloadTask! { return task as NSURLSessionDownloadTask }
  890. var downloadProgress: ((Int64, Int64, Int64) -> Void)?
  891. var resumeData: NSData?
  892. override var data: NSData? { return resumeData }
  893. var downloadTaskDidFinishDownloadingToURL: ((NSURLSession!, NSURLSessionDownloadTask!, NSURL) -> (NSURL))?
  894. var downloadTaskDidWriteData: ((NSURLSession!, NSURLSessionDownloadTask!, Int64, Int64, Int64) -> Void)?
  895. var downloadTaskDidResumeAtOffset: ((NSURLSession!, NSURLSessionDownloadTask!, Int64, Int64) -> Void)?
  896. // MARK: NSURLSessionDownloadDelegate
  897. func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL) {
  898. if downloadTaskDidFinishDownloadingToURL != nil {
  899. let destination = downloadTaskDidFinishDownloadingToURL!(session, downloadTask, location)
  900. var fileManagerError: NSError?
  901. NSFileManager.defaultManager().moveItemAtURL(location, toURL: destination, error: &fileManagerError)
  902. if fileManagerError != nil {
  903. error = fileManagerError
  904. }
  905. }
  906. }
  907. func URLSession(session: NSURLSession!, downloadTask: NSURLSessionDownloadTask!, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
  908. downloadTaskDidWriteData?(session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite)
  909. downloadProgress?(bytesWritten, totalBytesWritten, totalBytesExpectedToWrite)
  910. progress.totalUnitCount = totalBytesExpectedToWrite
  911. progress.completedUnitCount = totalBytesWritten
  912. }
  913. func URLSession(session: NSURLSession!, downloadTask: NSURLSessionDownloadTask!, didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64) {
  914. downloadTaskDidResumeAtOffset?(session, downloadTask, fileOffset, expectedTotalBytes)
  915. progress.totalUnitCount = expectedTotalBytes
  916. progress.completedUnitCount = fileOffset
  917. }
  918. }
  919. }
  920. // MARK: - Printable
  921. extension Request: Printable {
  922. /// The textual representation used when written to an `OutputStreamType`, which includes the HTTP method and URL, as well as the response status code if a response has been received.
  923. public var description: String {
  924. var components: [String] = []
  925. if request.HTTPMethod != nil {
  926. components.append(request.HTTPMethod!)
  927. }
  928. components.append(request.URL.absoluteString!)
  929. if response != nil {
  930. components.append("(\(response!.statusCode))")
  931. }
  932. return join(" ", components)
  933. }
  934. }
  935. extension Request: DebugPrintable {
  936. func cURLRepresentation() -> String {
  937. var components: [String] = ["$ curl -i"]
  938. let URL = request.URL
  939. if request.HTTPMethod != nil && request.HTTPMethod != "GET" {
  940. components.append("-X \(request.HTTPMethod!)")
  941. }
  942. if let credentialStorage = session.configuration.URLCredentialStorage {
  943. let protectionSpace = NSURLProtectionSpace(host: URL.host!, port: URL.port ?? 0, `protocol`: URL.scheme, realm: URL.host, authenticationMethod: NSURLAuthenticationMethodHTTPBasic)
  944. if let credentials = credentialStorage.credentialsForProtectionSpace(protectionSpace)?.values.array {
  945. for credential: NSURLCredential in (credentials as [NSURLCredential]) {
  946. components.append("-u \(credential.user):\(credential.password)")
  947. }
  948. } else {
  949. if let credential = delegate.credential {
  950. components.append("-u \(credential.user):\(credential.password)")
  951. }
  952. }
  953. }
  954. if let cookieStorage = session.configuration.HTTPCookieStorage {
  955. if let cookies = cookieStorage.cookiesForURL(URL) as? [NSHTTPCookie] {
  956. if !cookies.isEmpty {
  957. let string = cookies.reduce(""){ $0 + "\($1.name)=\($1.value);" }
  958. components.append("-b \"\(string.substringToIndex(string.endIndex.predecessor()))\"")
  959. }
  960. }
  961. }
  962. for (field, value) in request.allHTTPHeaderFields! {
  963. switch field {
  964. case "Cookie":
  965. continue
  966. default:
  967. components.append("-H \"\(field): \(value)\"")
  968. }
  969. }
  970. if let HTTPBody = request.HTTPBody {
  971. components.append("-d \"\(NSString(data: HTTPBody, encoding: NSUTF8StringEncoding))\"")
  972. }
  973. components.append("\"\(URL.absoluteString!)\"")
  974. return join(" \\\n\t", components)
  975. }
  976. /// The textual representation used when written to an `OutputStreamType`, in the form of a cURL command.
  977. public var debugDescription: String {
  978. return cURLRepresentation()
  979. }
  980. }
  981. // MARK: - Response Serializers
  982. // MARK: String
  983. extension Request {
  984. /**
  985. Creates a response serializer that returns a string initialized from the response data with the specified string encoding.
  986. :param: encoding The string encoding. `NSUTF8StringEncoding` by default.
  987. :returns: A string response serializer.
  988. */
  989. public class func stringResponseSerializer(encoding: NSStringEncoding = NSUTF8StringEncoding) -> Serializer {
  990. return { (_, _, data) in
  991. let string = NSString(data: data!, encoding: encoding)
  992. return (string, nil)
  993. }
  994. }
  995. /**
  996. Adds a handler to be called once the request has finished.
  997. :param: completionHandler A closure to be executed once the request has finished. The closure takes 4 arguments: the URL request, the URL response, if one was received, the string, if one could be created from the URL response and data, and any error produced while creating the string.
  998. :returns: The request.
  999. */
  1000. public func responseString(completionHandler: (NSURLRequest, NSHTTPURLResponse?, String?, NSError?) -> Void) -> Self {
  1001. return responseString(completionHandler: completionHandler)
  1002. }
  1003. /**
  1004. Adds a handler to be called once the request has finished.
  1005. :param: encoding The string encoding. `NSUTF8StringEncoding` by default.
  1006. :param: completionHandler A closure to be executed once the request has finished. The closure takes 4 arguments: the URL request, the URL response, if one was received, the string, if one could be created from the URL response and data, and any error produced while creating the string.
  1007. :returns: The request.
  1008. */
  1009. public func responseString(encoding: NSStringEncoding = NSUTF8StringEncoding, completionHandler: (NSURLRequest, NSHTTPURLResponse?, String?, NSError?) -> Void) -> Self {
  1010. return response(serializer: Request.stringResponseSerializer(encoding: encoding), completionHandler: { request, response, string, error in
  1011. completionHandler(request, response, string as? String, error)
  1012. })
  1013. }
  1014. }
  1015. // MARK: JSON
  1016. extension Request {
  1017. /**
  1018. Creates a response serializer that returns a JSON object constructed from the response data using `NSJSONSerialization` with the specified reading options.
  1019. :param: options The JSON serialization reading options. `.AllowFragments` by default.
  1020. :returns: A JSON object response serializer.
  1021. */
  1022. public class func JSONResponseSerializer(options: NSJSONReadingOptions = .AllowFragments) -> Serializer {
  1023. return { (request, response, data) in
  1024. var serializationError: NSError?
  1025. let JSON: AnyObject? = NSJSONSerialization.JSONObjectWithData(data!, options: options, error: &serializationError)
  1026. return (JSON, serializationError)
  1027. }
  1028. }
  1029. /**
  1030. Adds a handler to be called once the request has finished.
  1031. :param: completionHandler A closure to be executed once the request has finished. The closure takes 4 arguments: the URL request, the URL response, if one was received, the JSON object, if one could be created from the URL response and data, and any error produced while creating the JSON object.
  1032. :returns: The request.
  1033. */
  1034. public func responseJSON(completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Self {
  1035. return responseJSON(completionHandler: completionHandler)
  1036. }
  1037. /**
  1038. Adds a handler to be called once the request has finished.
  1039. :param: options The JSON serialization reading options. `.AllowFragments` by default.
  1040. :param: completionHandler A closure to be executed once the request has finished. The closure takes 4 arguments: the URL request, the URL response, if one was received, the JSON object, if one could be created from the URL response and data, and any error produced while creating the JSON object.
  1041. :returns: The request.
  1042. */
  1043. public func responseJSON(options: NSJSONReadingOptions = .AllowFragments, completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Self {
  1044. return response(serializer: Request.JSONResponseSerializer(options: options), completionHandler: { (request, response, JSON, error) in
  1045. completionHandler(request, response, JSON, error)
  1046. })
  1047. }
  1048. }
  1049. // MARK: Property List
  1050. extension Request {
  1051. /**
  1052. Creates a response serializer that returns an object constructed from the response data using `NSPropertyListSerialization` with the specified reading options.
  1053. :param: options The property list reading options. `0` by default.
  1054. :returns: A property list object response serializer.
  1055. */
  1056. public class func propertyListResponseSerializer(options: NSPropertyListReadOptions = 0) -> Serializer {
  1057. return { (request, response, data) in
  1058. var propertyListSerializationError: NSError?
  1059. let plist: AnyObject? = NSPropertyListSerialization.propertyListWithData(data!, options: options, format: nil, error: &propertyListSerializationError)
  1060. return (plist, propertyListSerializationError)
  1061. }
  1062. }
  1063. /**
  1064. Adds a handler to be called once the request has finished.
  1065. :param: completionHandler A closure to be executed once the request has finished. The closure takes 4 arguments: the URL request, the URL response, if one was received, the property list, if one could be created from the URL response and data, and any error produced while creating the property list.
  1066. :returns: The request.
  1067. */
  1068. public func responsePropertyList(completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Self {
  1069. return responsePropertyList(completionHandler: completionHandler)
  1070. }
  1071. /**
  1072. Adds a handler to be called once the request has finished.
  1073. :param: options The property list reading options. `0` by default.
  1074. :param: completionHandler A closure to be executed once the request has finished. The closure takes 4 arguments: the URL request, the URL response, if one was received, the property list, if one could be created from the URL response and data, and any error produced while creating the property list.
  1075. :returns: The request.
  1076. */
  1077. public func responsePropertyList(options: NSPropertyListReadOptions = 0, completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Self {
  1078. return response(serializer: Request.propertyListResponseSerializer(options: options), completionHandler: { (request, response, plist, error) in
  1079. completionHandler(request, response, plist, error)
  1080. })
  1081. }
  1082. }
  1083. // MARK: - Convenience -
  1084. private func URLRequest(method: Method, URLString: URLStringConvertible) -> NSURLRequest {
  1085. let mutableURLRequest = NSMutableURLRequest(URL: NSURL(string: URLString.URLString))
  1086. mutableURLRequest.HTTPMethod = method.toRaw()
  1087. return mutableURLRequest
  1088. }
  1089. // MARK: - Request
  1090. /**
  1091. Creates a request using the shared manager instance for the specified method, URL string, parameters, and parameter encoding.
  1092. :param: method The HTTP method.
  1093. :param: URLString The URL string.
  1094. :param: parameters The parameters. `nil` by default.
  1095. :param: encoding The parameter encoding. `.URL` by default.
  1096. :returns: The created request.
  1097. */
  1098. public func request(method: Method, URLString: URLStringConvertible, parameters: [String: AnyObject]? = nil, encoding: ParameterEncoding = .URL) -> Request {
  1099. return request(encoding.encode(URLRequest(method, URLString), parameters: parameters).0)
  1100. }
  1101. /**
  1102. Creates a request using the shared manager instance for the specified URL request.
  1103. If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
  1104. :param: URLRequest The URL request
  1105. :returns: The created request.
  1106. */
  1107. public func request(URLRequest: URLRequestConvertible) -> Request {
  1108. return Manager.sharedInstance.request(URLRequest.URLRequest)
  1109. }
  1110. // MARK: - Upload
  1111. // MARK: File
  1112. /**
  1113. Creates an upload request using the shared manager instance for the specified method, URL string, and file.
  1114. :param: method The HTTP method.
  1115. :param: URLString The URL string.
  1116. :param: file The file to upload.
  1117. :returns: The created upload request.
  1118. */
  1119. public func upload(method: Method, URLString: URLStringConvertible, file: NSURL) -> Request {
  1120. return Manager.sharedInstance.upload(URLRequest(method, URLString), file: file)
  1121. }
  1122. /**
  1123. Creates an upload request using the shared manager instance for the specified URL request and file.
  1124. :param: URLRequest The URL request.
  1125. :param: file The file to upload.
  1126. :returns: The created upload request.
  1127. */
  1128. public func upload(URLRequest: URLRequestConvertible, file: NSURL) -> Request {
  1129. return Manager.sharedInstance.upload(URLRequest, file: file)
  1130. }
  1131. // MARK: Data
  1132. /**
  1133. Creates an upload request using the shared manager instance for the specified method, URL string, and data.
  1134. :param: method The HTTP method.
  1135. :param: URLString The URL string.
  1136. :param: data The data to upload.
  1137. :returns: The created upload request.
  1138. */
  1139. public func upload(method: Method, URLString: URLStringConvertible, data: NSData) -> Request {
  1140. return Manager.sharedInstance.upload(URLRequest(method, URLString), data: data)
  1141. }
  1142. /**
  1143. Creates an upload request using the shared manager instance for the specified URL request and data.
  1144. :param: URLRequest The URL request.
  1145. :param: data The data to upload.
  1146. :returns: The created upload request.
  1147. */
  1148. public func upload(URLRequest: URLRequestConvertible, data: NSData) -> Request {
  1149. return Manager.sharedInstance.upload(URLRequest, data: data)
  1150. }
  1151. // MARK: Stream
  1152. /**
  1153. Creates an upload request using the shared manager instance for the specified method, URL string, and stream.
  1154. :param: method The HTTP method.
  1155. :param: URLString The URL string.
  1156. :param: stream The stream to upload.
  1157. :returns: The created upload request.
  1158. */
  1159. public func upload(method: Method, URLString: URLStringConvertible, stream: NSInputStream) -> Request {
  1160. return Manager.sharedInstance.upload(URLRequest(method, URLString), stream: stream)
  1161. }
  1162. /**
  1163. Creates an upload request using the shared manager instance for the specified URL request and stream.
  1164. :param: URLRequest The URL request.
  1165. :param: stream The stream to upload.
  1166. :returns: The created upload request.
  1167. */
  1168. public func upload(URLRequest: URLRequestConvertible, stream: NSInputStream) -> Request {
  1169. return Manager.sharedInstance.upload(URLRequest, stream: stream)
  1170. }
  1171. // MARK: - Download
  1172. // MARK: URL Request
  1173. /**
  1174. Creates a download request using the shared manager instance for the specified method and URL string.
  1175. :param: method The HTTP method.
  1176. :param: URLString The URL string.
  1177. :param: destination The closure used to determine the destination of the downloaded file.
  1178. :returns: The created download request.
  1179. */
  1180. public func download(method: Method, URLString: URLStringConvertible, destination: Request.DownloadFileDestination) -> Request {
  1181. return Manager.sharedInstance.download(URLRequest(method, URLString), destination: destination)
  1182. }
  1183. /**
  1184. Creates a download request using the shared manager instance for the specified URL request.
  1185. :param: URLRequest The URL request.
  1186. :param: destination The closure used to determine the destination of the downloaded file.
  1187. :returns: The created download request.
  1188. */
  1189. public func download(URLRequest: URLRequestConvertible, destination: Request.DownloadFileDestination) -> Request {
  1190. return Manager.sharedInstance.download(URLRequest, destination: destination)
  1191. }
  1192. // MARK: Resume Data
  1193. /**
  1194. Creates a request using the shared manager instance for downloading from the resume data produced from a previous request cancellation.
  1195. :param: resumeData The resume data. This is an opaque data blob produced by `NSURLSessionDownloadTask` when a task is cancelled. See `NSURLSession -downloadTaskWithResumeData:` for additional information.
  1196. :param: destination The closure used to determine the destination of the downloaded file.
  1197. :returns: The created download request.
  1198. */
  1199. public func download(resumeData data: NSData, destination: Request.DownloadFileDestination) -> Request {
  1200. return Manager.sharedInstance.download(data, destination: destination)
  1201. }