Alamofire.swift 64 KB

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