Alamofire.swift 58 KB

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