Alamofire.swift 63 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569
  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. 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.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` protocol 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` protocol 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. private let queue = dispatch_queue_create(nil, DISPATCH_QUEUE_SERIAL)
  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: nil)
  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(queue) {
  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. self.queue = {
  545. let label: String = "com.alamofire.task-\(task.taskIdentifier)"
  546. let queue = dispatch_queue_create((label as NSString).UTF8String, DISPATCH_QUEUE_SERIAL)
  547. dispatch_suspend(queue)
  548. return queue
  549. }()
  550. }
  551. // MARK: NSURLSessionTaskDelegate
  552. func URLSession(session: NSURLSession!, task: NSURLSessionTask!, willPerformHTTPRedirection response: NSHTTPURLResponse!, newRequest request: NSURLRequest!, completionHandler: ((NSURLRequest!) -> Void)!) {
  553. var redirectRequest = request
  554. if taskWillPerformHTTPRedirection != nil {
  555. redirectRequest = taskWillPerformHTTPRedirection!(session, task, response, request)
  556. }
  557. completionHandler(redirectRequest)
  558. }
  559. func URLSession(session: NSURLSession!, task: NSURLSessionTask!, didReceiveChallenge challenge: NSURLAuthenticationChallenge!, completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential!) -> Void)!) {
  560. var disposition: NSURLSessionAuthChallengeDisposition = .PerformDefaultHandling
  561. var credential: NSURLCredential?
  562. if taskDidReceiveChallenge != nil {
  563. (disposition, credential) = taskDidReceiveChallenge!(session, task, challenge)
  564. } else {
  565. if challenge.previousFailureCount > 0 {
  566. disposition = .CancelAuthenticationChallenge
  567. } else {
  568. // TODO: Incorporate Trust Evaluation & TLS Chain Validation
  569. switch challenge.protectionSpace.authenticationMethod! {
  570. case NSURLAuthenticationMethodServerTrust:
  571. credential = NSURLCredential(forTrust: challenge.protectionSpace.serverTrust)
  572. default:
  573. credential = self.credential ?? session.configuration.URLCredentialStorage?.defaultCredentialForProtectionSpace(challenge.protectionSpace)
  574. }
  575. if credential != nil {
  576. disposition = .UseCredential
  577. }
  578. }
  579. }
  580. completionHandler(disposition, credential)
  581. }
  582. func URLSession(session: NSURLSession!, task: NSURLSessionTask!, needNewBodyStream completionHandler: ((NSInputStream!) -> Void)!) {
  583. var bodyStream: NSInputStream?
  584. if taskNeedNewBodyStream != nil {
  585. bodyStream = taskNeedNewBodyStream!(session, task)
  586. }
  587. completionHandler(bodyStream)
  588. }
  589. func URLSession(session: NSURLSession!, task: NSURLSessionTask!, didCompleteWithError error: NSError!) {
  590. if error != nil {
  591. self.error = error
  592. }
  593. dispatch_resume(queue)
  594. }
  595. }
  596. class DataTaskDelegate: TaskDelegate, NSURLSessionDataDelegate {
  597. var dataTask: NSURLSessionDataTask! { return task as NSURLSessionDataTask }
  598. private var mutableData: NSMutableData
  599. override var data: NSData? {
  600. return mutableData
  601. }
  602. private var expectedContentLength: Int64?
  603. var dataTaskDidReceiveResponse: ((NSURLSession!, NSURLSessionDataTask!, NSURLResponse!) -> (NSURLSessionResponseDisposition))?
  604. var dataTaskDidBecomeDownloadTask: ((NSURLSession!, NSURLSessionDataTask!) -> Void)?
  605. var dataTaskDidReceiveData: ((NSURLSession!, NSURLSessionDataTask!, NSData!) -> Void)?
  606. var dataTaskWillCacheResponse: ((NSURLSession!, NSURLSessionDataTask!, NSCachedURLResponse!) -> (NSCachedURLResponse))?
  607. var dataProgress: ((bytesReceived: Int64, totalBytesReceived: Int64, totalBytesExpectedToReceive: Int64) -> Void)?
  608. override init(task: NSURLSessionTask) {
  609. self.mutableData = NSMutableData()
  610. super.init(task: task)
  611. }
  612. // MARK: NSURLSessionDataDelegate
  613. func URLSession(session: NSURLSession!, dataTask: NSURLSessionDataTask!, didReceiveResponse response: NSURLResponse!, completionHandler: ((NSURLSessionResponseDisposition) -> Void)!) {
  614. var disposition: NSURLSessionResponseDisposition = .Allow
  615. expectedContentLength = response.expectedContentLength
  616. if dataTaskDidReceiveResponse != nil {
  617. disposition = dataTaskDidReceiveResponse!(session, dataTask, response)
  618. }
  619. completionHandler(disposition)
  620. }
  621. func URLSession(session: NSURLSession!, dataTask: NSURLSessionDataTask!, didBecomeDownloadTask downloadTask: NSURLSessionDownloadTask!) {
  622. dataTaskDidBecomeDownloadTask?(session, dataTask)
  623. }
  624. func URLSession(session: NSURLSession!, dataTask: NSURLSessionDataTask!, didReceiveData data: NSData!) {
  625. dataTaskDidReceiveData?(session, dataTask, data)
  626. mutableData.appendData(data)
  627. if let expectedContentLength = dataTask?.response?.expectedContentLength {
  628. dataProgress?(bytesReceived: Int64(data.length), totalBytesReceived: Int64(mutableData.length), totalBytesExpectedToReceive: expectedContentLength)
  629. }
  630. }
  631. func URLSession(session: NSURLSession!, dataTask: NSURLSessionDataTask!, willCacheResponse proposedResponse: NSCachedURLResponse!, completionHandler: ((NSCachedURLResponse!) -> Void)!) {
  632. var cachedResponse = proposedResponse
  633. if dataTaskWillCacheResponse != nil {
  634. cachedResponse = dataTaskWillCacheResponse!(session, dataTask, proposedResponse)
  635. }
  636. completionHandler(cachedResponse)
  637. }
  638. }
  639. }
  640. // MARK: - Validation
  641. extension Request {
  642. /**
  643. A closure used to validate a request that takes a URL request and URL response, and returns whether the request was valid.
  644. */
  645. public typealias Validation = (NSURLRequest, NSHTTPURLResponse) -> (Bool)
  646. /**
  647. Validates the request, using the specified closure.
  648. If validation fails, subsequent calls to response handlers will have an associated error.
  649. :param: validation A closure to validate the request.
  650. :returns: The request.
  651. */
  652. public func validate(validation: Validation) -> Self {
  653. return response(priority: DISPATCH_QUEUE_PRIORITY_HIGH, queue: self.delegate.queue, serializer: Request.responseDataSerializer()){ (request, response, data, error) in
  654. if response != nil && error == nil {
  655. if !validation(request, response!) {
  656. self.delegate.error = NSError(domain: AlamofireErrorDomain, code: -1, userInfo: nil)
  657. }
  658. }
  659. }
  660. }
  661. // MARK: Status Code
  662. private class func response(response: NSHTTPURLResponse, hasAcceptableStatusCode statusCodes: [Int]) -> Bool {
  663. return contains(statusCodes, response.statusCode)
  664. }
  665. /**
  666. Validates that the response has a status code in the specified range.
  667. If validation fails, subsequent calls to response handlers will have an associated error.
  668. :param: range The range of acceptable status codes.
  669. :returns: The request.
  670. */
  671. public func validate(statusCode range: Range<Int>) -> Self {
  672. return validate { (_, response) in
  673. return Request.response(response, hasAcceptableStatusCode: range.map({$0}))
  674. }
  675. }
  676. /**
  677. Validates that the response has a status code in the specified array.
  678. If validation fails, subsequent calls to response handlers will have an associated error.
  679. :param: array The acceptable status codes.
  680. :returns: The request.
  681. */
  682. public func validate(statusCode array: [Int]) -> Self {
  683. return validate { (_, response) in
  684. return Request.response(response, hasAcceptableStatusCode: array)
  685. }
  686. }
  687. // MARK: Content-Type
  688. private struct MIMEType {
  689. let type: String
  690. let subtype: String
  691. init(_ string: String) {
  692. let components = string.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).substringToIndex(string.rangeOfString(";")?.endIndex ?? string.endIndex).componentsSeparatedByString("/")
  693. self.type = components.first!
  694. self.subtype = components.last!
  695. }
  696. func matches(MIME: MIMEType) -> Bool {
  697. switch (type, subtype) {
  698. case ("*", "*"), ("*", MIME.subtype), (MIME.type, "*"), (MIME.type, MIME.subtype):
  699. return true
  700. default:
  701. return false
  702. }
  703. }
  704. }
  705. private class func response(response: NSHTTPURLResponse, hasAcceptableContentType contentTypes: [String]) -> Bool {
  706. if response.MIMEType != nil {
  707. let responseMIMEType = MIMEType(response.MIMEType!)
  708. for acceptableMIMEType in contentTypes.map({MIMEType($0)}) {
  709. if acceptableMIMEType.matches(responseMIMEType) {
  710. return true
  711. }
  712. }
  713. }
  714. return false
  715. }
  716. /**
  717. Validates that the response has a content type in the specified array.
  718. If validation fails, subsequent calls to response handlers will have an associated error.
  719. :param: contentType The acceptable content types, which may specify wildcard types and/or subtypes.
  720. :returns: The request.
  721. */
  722. public func validate(contentType array: [String]) -> Self {
  723. return validate {(_, response) in
  724. return Request.response(response, hasAcceptableContentType: array)
  725. }
  726. }
  727. // MARK: Automatic
  728. /**
  729. 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.
  730. If validation fails, subsequent calls to response handlers will have an associated error.
  731. :returns: The request.
  732. */
  733. public func validate() -> Self {
  734. let acceptableStatusCodes: Range<Int> = 200..<300
  735. let acceptableContentTypes: [String] = {
  736. if let accept = self.request.valueForHTTPHeaderField("Accept") {
  737. return accept.componentsSeparatedByString(",")
  738. }
  739. return ["*/*"]
  740. }()
  741. return validate(statusCode: acceptableStatusCodes).validate(contentType: acceptableContentTypes)
  742. }
  743. }
  744. // MARK: - Upload
  745. extension Manager {
  746. private enum Uploadable {
  747. case Data(NSURLRequest, NSData)
  748. case File(NSURLRequest, NSURL)
  749. case Stream(NSURLRequest, NSInputStream)
  750. }
  751. private func upload(uploadable: Uploadable) -> Request {
  752. var uploadTask: NSURLSessionUploadTask!
  753. var stream: NSInputStream?
  754. switch uploadable {
  755. case .Data(let request, let data):
  756. uploadTask = session.uploadTaskWithRequest(request, fromData: data)
  757. case .File(let request, let fileURL):
  758. uploadTask = session.uploadTaskWithRequest(request, fromFile: fileURL)
  759. case .Stream(let request, var stream):
  760. uploadTask = session.uploadTaskWithStreamedRequest(request)
  761. }
  762. let request = Request(session: session, task: uploadTask)
  763. if stream != nil {
  764. request.delegate.taskNeedNewBodyStream = { _, _ in
  765. return stream
  766. }
  767. }
  768. delegate[request.delegate.task] = request.delegate
  769. if startRequestsImmediately {
  770. request.resume()
  771. }
  772. return request
  773. }
  774. // MARK: File
  775. /**
  776. Creates a request for uploading a file to the specified URL request.
  777. If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
  778. :param: URLRequest The URL request
  779. :param: file The file to upload
  780. :returns: The created upload request.
  781. */
  782. public func upload(URLRequest: URLRequestConvertible, file: NSURL) -> Request {
  783. return upload(.File(URLRequest.URLRequest, file))
  784. }
  785. // MARK: Data
  786. /**
  787. Creates a request for uploading data to the specified URL request.
  788. If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
  789. :param: URLRequest The URL request
  790. :param: data The data to upload
  791. :returns: The created upload request.
  792. */
  793. public func upload(URLRequest: URLRequestConvertible, data: NSData) -> Request {
  794. return upload(.Data(URLRequest.URLRequest, data))
  795. }
  796. // MARK: Stream
  797. /**
  798. Creates a request for uploading a stream to the specified URL request.
  799. If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
  800. :param: URLRequest The URL request
  801. :param: stream The stream to upload
  802. :returns: The created upload request.
  803. */
  804. public func upload(URLRequest: URLRequestConvertible, stream: NSInputStream) -> Request {
  805. return upload(.Stream(URLRequest.URLRequest, stream))
  806. }
  807. }
  808. extension Request {
  809. class UploadTaskDelegate: DataTaskDelegate {
  810. var uploadTask: NSURLSessionUploadTask! { return task as NSURLSessionUploadTask }
  811. var uploadProgress: ((Int64, Int64, Int64) -> Void)!
  812. // MARK: NSURLSessionTaskDelegate
  813. func URLSession(session: NSURLSession!, task: NSURLSessionTask!, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
  814. if uploadProgress != nil {
  815. uploadProgress(bytesSent, totalBytesSent, totalBytesExpectedToSend)
  816. }
  817. progress.totalUnitCount = totalBytesExpectedToSend
  818. progress.completedUnitCount = totalBytesSent
  819. }
  820. }
  821. }
  822. // MARK: - Download
  823. extension Manager {
  824. private enum Downloadable {
  825. case Request(NSURLRequest)
  826. case ResumeData(NSData)
  827. }
  828. private func download(downloadable: Downloadable, destination: (NSURL, NSHTTPURLResponse) -> (NSURL)) -> Request {
  829. var downloadTask: NSURLSessionDownloadTask!
  830. switch downloadable {
  831. case .Request(let request):
  832. downloadTask = session.downloadTaskWithRequest(request)
  833. case .ResumeData(let resumeData):
  834. downloadTask = session.downloadTaskWithResumeData(resumeData)
  835. }
  836. let request = Request(session: session, task: downloadTask)
  837. if let downloadDelegate = request.delegate as? Request.DownloadTaskDelegate {
  838. downloadDelegate.downloadTaskDidFinishDownloadingToURL = { (session, downloadTask, URL) in
  839. return destination(URL, downloadTask.response as NSHTTPURLResponse)
  840. }
  841. }
  842. delegate[request.delegate.task] = request.delegate
  843. if startRequestsImmediately {
  844. request.resume()
  845. }
  846. return request
  847. }
  848. // MARK: Request
  849. /**
  850. Creates a request for downloading from the specified URL request.
  851. If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
  852. :param: URLRequest The URL request
  853. :param: destination The closure used to determine the destination of the downloaded file.
  854. :returns: The created download request.
  855. */
  856. public func download(URLRequest: URLRequestConvertible, destination: (NSURL, NSHTTPURLResponse) -> (NSURL)) -> Request {
  857. return download(.Request(URLRequest.URLRequest), destination: destination)
  858. }
  859. // MARK: Resume Data
  860. /**
  861. Creates a request for downloading from the resume data produced from a previous request cancellation.
  862. If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
  863. :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.
  864. :param: destination The closure used to determine the destination of the downloaded file.
  865. :returns: The created download request.
  866. */
  867. public func download(resumeData: NSData, destination: Request.DownloadFileDestination) -> Request {
  868. return download(.ResumeData(resumeData), destination: destination)
  869. }
  870. }
  871. extension Request {
  872. /**
  873. 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.
  874. */
  875. public typealias DownloadFileDestination = (NSURL, NSHTTPURLResponse) -> (NSURL)
  876. /**
  877. 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.
  878. :param: directory The search path directory. `.DocumentDirectory` by default.
  879. :param: domain The search path domain mask. `.UserDomainMask` by default.
  880. :returns: A download file destination closure.
  881. */
  882. public class func suggestedDownloadDestination(directory: NSSearchPathDirectory = .DocumentDirectory, domain: NSSearchPathDomainMask = .UserDomainMask) -> DownloadFileDestination {
  883. return { (temporaryURL, response) -> (NSURL) in
  884. if let directoryURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0] as? NSURL {
  885. return directoryURL.URLByAppendingPathComponent(response.suggestedFilename!)
  886. }
  887. return temporaryURL
  888. }
  889. }
  890. class DownloadTaskDelegate: TaskDelegate, NSURLSessionDownloadDelegate {
  891. var downloadTask: NSURLSessionDownloadTask! { return task as NSURLSessionDownloadTask }
  892. var downloadProgress: ((Int64, Int64, Int64) -> Void)?
  893. var resumeData: NSData?
  894. override var data: NSData? { return resumeData }
  895. var downloadTaskDidFinishDownloadingToURL: ((NSURLSession!, NSURLSessionDownloadTask!, NSURL) -> (NSURL))?
  896. var downloadTaskDidWriteData: ((NSURLSession!, NSURLSessionDownloadTask!, Int64, Int64, Int64) -> Void)?
  897. var downloadTaskDidResumeAtOffset: ((NSURLSession!, NSURLSessionDownloadTask!, Int64, Int64) -> Void)?
  898. // MARK: NSURLSessionDownloadDelegate
  899. func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL) {
  900. if downloadTaskDidFinishDownloadingToURL != nil {
  901. let destination = downloadTaskDidFinishDownloadingToURL!(session, downloadTask, location)
  902. var fileManagerError: NSError?
  903. NSFileManager.defaultManager().moveItemAtURL(location, toURL: destination, error: &fileManagerError)
  904. if fileManagerError != nil {
  905. error = fileManagerError
  906. }
  907. }
  908. }
  909. func URLSession(session: NSURLSession!, downloadTask: NSURLSessionDownloadTask!, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
  910. downloadTaskDidWriteData?(session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite)
  911. downloadProgress?(bytesWritten, totalBytesWritten, totalBytesExpectedToWrite)
  912. progress.totalUnitCount = totalBytesExpectedToWrite
  913. progress.completedUnitCount = totalBytesWritten
  914. }
  915. func URLSession(session: NSURLSession!, downloadTask: NSURLSessionDownloadTask!, didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64) {
  916. downloadTaskDidResumeAtOffset?(session, downloadTask, fileOffset, expectedTotalBytes)
  917. progress.totalUnitCount = expectedTotalBytes
  918. progress.completedUnitCount = fileOffset
  919. }
  920. }
  921. }
  922. // MARK: - Printable
  923. extension Request: Printable {
  924. /// 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.
  925. public var description: String {
  926. var components: [String] = []
  927. if request.HTTPMethod != nil {
  928. components.append(request.HTTPMethod!)
  929. }
  930. components.append(request.URL.absoluteString!)
  931. if response != nil {
  932. components.append("(\(response!.statusCode))")
  933. }
  934. return join(" ", components)
  935. }
  936. }
  937. extension Request: DebugPrintable {
  938. func cURLRepresentation() -> String {
  939. var components: [String] = ["$ curl -i"]
  940. let URL = request.URL
  941. if request.HTTPMethod != nil && request.HTTPMethod != "GET" {
  942. components.append("-X \(request.HTTPMethod!)")
  943. }
  944. if let credentialStorage = session.configuration.URLCredentialStorage {
  945. let protectionSpace = NSURLProtectionSpace(host: URL.host!, port: URL.port ?? 0, `protocol`: URL.scheme, realm: URL.host, authenticationMethod: NSURLAuthenticationMethodHTTPBasic)
  946. if let credentials = credentialStorage.credentialsForProtectionSpace(protectionSpace)?.values.array {
  947. for credential: NSURLCredential in (credentials as [NSURLCredential]) {
  948. components.append("-u \(credential.user):\(credential.password)")
  949. }
  950. } else {
  951. if let credential = delegate.credential {
  952. components.append("-u \(credential.user):\(credential.password)")
  953. }
  954. }
  955. }
  956. if let cookieStorage = session.configuration.HTTPCookieStorage {
  957. if let cookies = cookieStorage.cookiesForURL(URL) as? [NSHTTPCookie] {
  958. if !cookies.isEmpty {
  959. let string = cookies.reduce(""){ $0 + "\($1.name)=\($1.value);" }
  960. components.append("-b \"\(string.substringToIndex(string.endIndex.predecessor()))\"")
  961. }
  962. }
  963. }
  964. for (field, value) in request.allHTTPHeaderFields! {
  965. switch field {
  966. case "Cookie":
  967. continue
  968. default:
  969. components.append("-H \"\(field): \(value)\"")
  970. }
  971. }
  972. if let HTTPBody = request.HTTPBody {
  973. components.append("-d \"\(NSString(data: HTTPBody, encoding: NSUTF8StringEncoding))\"")
  974. }
  975. components.append("\"\(URL.absoluteString!)\"")
  976. return join(" \\\n\t", components)
  977. }
  978. /// The textual representation used when written to an `OutputStreamType`, in the form of a cURL command.
  979. public var debugDescription: String {
  980. return cURLRepresentation()
  981. }
  982. }
  983. // MARK: - Response Serializers
  984. // MARK: String
  985. extension Request {
  986. /**
  987. Creates a response serializer that returns a string initialized from the response data with the specified string encoding.
  988. :param: encoding The string encoding. `NSUTF8StringEncoding` by default.
  989. :returns: A string response serializer.
  990. */
  991. public class func stringResponseSerializer(encoding: NSStringEncoding = NSUTF8StringEncoding) -> Serializer {
  992. return { (_, _, data) in
  993. let string = NSString(data: data!, encoding: encoding)
  994. return (string, nil)
  995. }
  996. }
  997. /**
  998. Adds a handler to be called once the request has finished.
  999. :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.
  1000. :returns: The request.
  1001. */
  1002. public func responseString(completionHandler: (NSURLRequest, NSHTTPURLResponse?, String?, NSError?) -> Void) -> Self {
  1003. return responseString(completionHandler: completionHandler)
  1004. }
  1005. /**
  1006. Adds a handler to be called once the request has finished.
  1007. :param: encoding The string encoding. `NSUTF8StringEncoding` by default.
  1008. :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.
  1009. :returns: The request.
  1010. */
  1011. public func responseString(encoding: NSStringEncoding = NSUTF8StringEncoding, completionHandler: (NSURLRequest, NSHTTPURLResponse?, String?, NSError?) -> Void) -> Self {
  1012. return response(serializer: Request.stringResponseSerializer(encoding: encoding), completionHandler: { request, response, string, error in
  1013. completionHandler(request, response, string as? String, error)
  1014. })
  1015. }
  1016. }
  1017. // MARK: JSON
  1018. extension Request {
  1019. /**
  1020. Creates a response serializer that returns a JSON object constructed from the response data using `NSJSONSerialization` with the specified reading options.
  1021. :param: options The JSON serialization reading options. `.AllowFragments` by default.
  1022. :returns: A JSON object response serializer.
  1023. */
  1024. public class func JSONResponseSerializer(options: NSJSONReadingOptions = .AllowFragments) -> Serializer {
  1025. return { (request, response, data) in
  1026. if data == nil {
  1027. return (nil, nil)
  1028. }
  1029. var serializationError: NSError?
  1030. let JSON: AnyObject? = NSJSONSerialization.JSONObjectWithData(data!, options: options, error: &serializationError)
  1031. return (JSON, serializationError)
  1032. }
  1033. }
  1034. /**
  1035. Adds a handler to be called once the request has finished.
  1036. :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.
  1037. :returns: The request.
  1038. */
  1039. public func responseJSON(completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Self {
  1040. return responseJSON(completionHandler: completionHandler)
  1041. }
  1042. /**
  1043. Adds a handler to be called once the request has finished.
  1044. :param: options The JSON serialization reading options. `.AllowFragments` by default.
  1045. :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.
  1046. :returns: The request.
  1047. */
  1048. public func responseJSON(options: NSJSONReadingOptions = .AllowFragments, completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Self {
  1049. return response(serializer: Request.JSONResponseSerializer(options: options), completionHandler: { (request, response, JSON, error) in
  1050. completionHandler(request, response, JSON, error)
  1051. })
  1052. }
  1053. }
  1054. // MARK: Property List
  1055. extension Request {
  1056. /**
  1057. Creates a response serializer that returns an object constructed from the response data using `NSPropertyListSerialization` with the specified reading options.
  1058. :param: options The property list reading options. `0` by default.
  1059. :returns: A property list object response serializer.
  1060. */
  1061. public class func propertyListResponseSerializer(options: NSPropertyListReadOptions = 0) -> Serializer {
  1062. return { (request, response, data) in
  1063. if data == nil {
  1064. return (nil, nil)
  1065. }
  1066. var propertyListSerializationError: NSError?
  1067. let plist: AnyObject? = NSPropertyListSerialization.propertyListWithData(data!, options: options, format: nil, error: &propertyListSerializationError)
  1068. return (plist, propertyListSerializationError)
  1069. }
  1070. }
  1071. /**
  1072. Adds a handler to be called once the request has finished.
  1073. :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.
  1074. :returns: The request.
  1075. */
  1076. public func responsePropertyList(completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Self {
  1077. return responsePropertyList(completionHandler: completionHandler)
  1078. }
  1079. /**
  1080. Adds a handler to be called once the request has finished.
  1081. :param: options The property list reading options. `0` by default.
  1082. :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.
  1083. :returns: The request.
  1084. */
  1085. public func responsePropertyList(options: NSPropertyListReadOptions = 0, completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Self {
  1086. return response(serializer: Request.propertyListResponseSerializer(options: options), completionHandler: { (request, response, plist, error) in
  1087. completionHandler(request, response, plist, error)
  1088. })
  1089. }
  1090. }
  1091. // MARK: - Convenience -
  1092. private func URLRequest(method: Method, URLString: URLStringConvertible) -> NSURLRequest {
  1093. let mutableURLRequest = NSMutableURLRequest(URL: NSURL(string: URLString.URLString))
  1094. mutableURLRequest.HTTPMethod = method.toRaw()
  1095. return mutableURLRequest
  1096. }
  1097. // MARK: - Request
  1098. /**
  1099. Creates a request using the shared manager instance for the specified method, URL string, parameters, and parameter encoding.
  1100. :param: method The HTTP method.
  1101. :param: URLString The URL string.
  1102. :param: parameters The parameters. `nil` by default.
  1103. :param: encoding The parameter encoding. `.URL` by default.
  1104. :returns: The created request.
  1105. */
  1106. public func request(method: Method, URLString: URLStringConvertible, parameters: [String: AnyObject]? = nil, encoding: ParameterEncoding = .URL) -> Request {
  1107. return request(encoding.encode(URLRequest(method, URLString), parameters: parameters).0)
  1108. }
  1109. /**
  1110. Creates a request using the shared manager instance for the specified URL request.
  1111. If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
  1112. :param: URLRequest The URL request
  1113. :returns: The created request.
  1114. */
  1115. public func request(URLRequest: URLRequestConvertible) -> Request {
  1116. return Manager.sharedInstance.request(URLRequest.URLRequest)
  1117. }
  1118. // MARK: - Upload
  1119. // MARK: File
  1120. /**
  1121. Creates an upload request using the shared manager instance for the specified method, URL string, and file.
  1122. :param: method The HTTP method.
  1123. :param: URLString The URL string.
  1124. :param: file The file to upload.
  1125. :returns: The created upload request.
  1126. */
  1127. public func upload(method: Method, URLString: URLStringConvertible, file: NSURL) -> Request {
  1128. return Manager.sharedInstance.upload(URLRequest(method, URLString), file: file)
  1129. }
  1130. /**
  1131. Creates an upload request using the shared manager instance for the specified URL request and file.
  1132. :param: URLRequest The URL request.
  1133. :param: file The file to upload.
  1134. :returns: The created upload request.
  1135. */
  1136. public func upload(URLRequest: URLRequestConvertible, file: NSURL) -> Request {
  1137. return Manager.sharedInstance.upload(URLRequest, file: file)
  1138. }
  1139. // MARK: Data
  1140. /**
  1141. Creates an upload request using the shared manager instance for the specified method, URL string, and data.
  1142. :param: method The HTTP method.
  1143. :param: URLString The URL string.
  1144. :param: data The data to upload.
  1145. :returns: The created upload request.
  1146. */
  1147. public func upload(method: Method, URLString: URLStringConvertible, data: NSData) -> Request {
  1148. return Manager.sharedInstance.upload(URLRequest(method, URLString), data: data)
  1149. }
  1150. /**
  1151. Creates an upload request using the shared manager instance for the specified URL request and data.
  1152. :param: URLRequest The URL request.
  1153. :param: data The data to upload.
  1154. :returns: The created upload request.
  1155. */
  1156. public func upload(URLRequest: URLRequestConvertible, data: NSData) -> Request {
  1157. return Manager.sharedInstance.upload(URLRequest, data: data)
  1158. }
  1159. // MARK: Stream
  1160. /**
  1161. Creates an upload request using the shared manager instance for the specified method, URL string, and stream.
  1162. :param: method The HTTP method.
  1163. :param: URLString The URL string.
  1164. :param: stream The stream to upload.
  1165. :returns: The created upload request.
  1166. */
  1167. public func upload(method: Method, URLString: URLStringConvertible, stream: NSInputStream) -> Request {
  1168. return Manager.sharedInstance.upload(URLRequest(method, URLString), stream: stream)
  1169. }
  1170. /**
  1171. Creates an upload request using the shared manager instance for the specified URL request and stream.
  1172. :param: URLRequest The URL request.
  1173. :param: stream The stream to upload.
  1174. :returns: The created upload request.
  1175. */
  1176. public func upload(URLRequest: URLRequestConvertible, stream: NSInputStream) -> Request {
  1177. return Manager.sharedInstance.upload(URLRequest, stream: stream)
  1178. }
  1179. // MARK: - Download
  1180. // MARK: URL Request
  1181. /**
  1182. Creates a download request using the shared manager instance for the specified method and URL string.
  1183. :param: method The HTTP method.
  1184. :param: URLString The URL string.
  1185. :param: destination The closure used to determine the destination of the downloaded file.
  1186. :returns: The created download request.
  1187. */
  1188. public func download(method: Method, URLString: URLStringConvertible, destination: Request.DownloadFileDestination) -> Request {
  1189. return Manager.sharedInstance.download(URLRequest(method, URLString), destination: destination)
  1190. }
  1191. /**
  1192. Creates a download request using the shared manager instance for the specified URL request.
  1193. :param: URLRequest The URL request.
  1194. :param: destination The closure used to determine the destination of the downloaded file.
  1195. :returns: The created download request.
  1196. */
  1197. public func download(URLRequest: URLRequestConvertible, destination: Request.DownloadFileDestination) -> Request {
  1198. return Manager.sharedInstance.download(URLRequest, destination: destination)
  1199. }
  1200. // MARK: Resume Data
  1201. /**
  1202. Creates a request using the shared manager instance for downloading from the resume data produced from a previous request cancellation.
  1203. :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.
  1204. :param: destination The closure used to determine the destination of the downloaded file.
  1205. :returns: The created download request.
  1206. */
  1207. public func download(resumeData data: NSData, destination: Request.DownloadFileDestination) -> Request {
  1208. return Manager.sharedInstance.download(data, destination: destination)
  1209. }