Alamofire.swift 65 KB

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