Alamofire.swift 69 KB

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