Alamofire.swift 63 KB

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