Request.swift 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  1. // Alamofire.swift
  2. //
  3. // Copyright (c) 2014–2015 Alamofire Software Foundation (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. Responsible for sending a request and receiving the response and associated data from the server, as well as managing its underlying `NSURLSessionTask`.
  25. */
  26. public class Request {
  27. // MARK: - Properties
  28. /// The delegate for the underlying task.
  29. public let delegate: TaskDelegate
  30. /// The underlying task.
  31. public var task: NSURLSessionTask { return delegate.task }
  32. /// The session belonging to the underlying task.
  33. public let session: NSURLSession
  34. /// The request sent or to be sent to the server.
  35. public var request: NSURLRequest { return task.originalRequest }
  36. /// The response received from the server, if any.
  37. public var response: NSHTTPURLResponse? { return task.response as? NSHTTPURLResponse }
  38. /// The progress of the request lifecycle.
  39. public var progress: NSProgress { return delegate.progress }
  40. // MARK: - Lifecycle
  41. init(session: NSURLSession, task: NSURLSessionTask) {
  42. self.session = session
  43. switch task {
  44. case is NSURLSessionUploadTask:
  45. self.delegate = UploadTaskDelegate(task: task)
  46. case is NSURLSessionDataTask:
  47. self.delegate = DataTaskDelegate(task: task)
  48. case is NSURLSessionDownloadTask:
  49. self.delegate = DownloadTaskDelegate(task: task)
  50. default:
  51. self.delegate = TaskDelegate(task: task)
  52. }
  53. }
  54. // MARK: - Authentication
  55. /**
  56. Associates an HTTP Basic credential with the request.
  57. :param: user The user.
  58. :param: password The password.
  59. :param: persistence The URL credential persistence. `.ForSession` by default.
  60. :returns: The request.
  61. */
  62. public func authenticate(#user: String, password: String, persistence: NSURLCredentialPersistence = .ForSession) -> Self {
  63. let credential = NSURLCredential(user: user, password: password, persistence: persistence)
  64. return authenticate(usingCredential: credential)
  65. }
  66. /**
  67. Associates a specified credential with the request.
  68. :param: credential The credential.
  69. :returns: The request.
  70. */
  71. public func authenticate(usingCredential credential: NSURLCredential) -> Self {
  72. self.delegate.credential = credential
  73. return self
  74. }
  75. // MARK: - Progress
  76. /**
  77. Sets a closure to be called periodically during the lifecycle of the request as data is written to or read from the server.
  78. - For uploads, the progress closure returns the bytes written, total bytes written, and total bytes expected to write.
  79. - For downloads and data tasks, the progress closure returns the bytes read, total bytes read, and total bytes expected to read.
  80. :param: closure The code to be executed periodically during the lifecycle of the request.
  81. :returns: The request.
  82. */
  83. public func progress(closure: ((Int64, Int64, Int64) -> Void)? = nil) -> Self {
  84. if let uploadDelegate = self.delegate as? UploadTaskDelegate {
  85. uploadDelegate.uploadProgress = closure
  86. } else if let dataDelegate = self.delegate as? DataTaskDelegate {
  87. dataDelegate.dataProgress = closure
  88. } else if let downloadDelegate = self.delegate as? DownloadTaskDelegate {
  89. downloadDelegate.downloadProgress = closure
  90. }
  91. return self
  92. }
  93. /**
  94. Sets a closure to be called periodically during the lifecycle of the request as data is read from the server.
  95. This closure returns the bytes most recently received from the server, not including data from previous calls. If this closure is set, data will only be available within this closure, and will not be saved elsewhere. It is also important to note that the `response` closure will be called with nil `responseData`.
  96. :param: closure The code to be executed periodically during the lifecycle of the request.
  97. :returns: The request.
  98. */
  99. public func stream(closure: (NSData -> Void)? = nil) -> Self {
  100. if let dataDelegate = self.delegate as? DataTaskDelegate {
  101. dataDelegate.dataStream = closure
  102. }
  103. return self
  104. }
  105. // MARK: - Response
  106. /**
  107. 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.
  108. */
  109. public typealias Serializer = (NSURLRequest, NSHTTPURLResponse?, NSData?) -> (AnyObject?, NSError?)
  110. /**
  111. Creates a response serializer that returns the associated data as-is.
  112. :returns: A data response serializer.
  113. */
  114. public class func responseDataSerializer() -> Serializer {
  115. return { request, response, data in
  116. return (data, nil)
  117. }
  118. }
  119. /**
  120. Adds a handler to be called once the request has finished.
  121. :param: completionHandler The code to be executed once the request has finished.
  122. :returns: The request.
  123. */
  124. public func response(completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Self {
  125. return response(serializer: Request.responseDataSerializer(), completionHandler: completionHandler)
  126. }
  127. /**
  128. Adds a handler to be called once the request has finished.
  129. :param: queue The queue on which the completion handler is dispatched.
  130. :param: serializer The closure responsible for serializing the request, response, and data.
  131. :param: completionHandler The code to be executed once the request has finished.
  132. :returns: The request.
  133. */
  134. public func response(queue: dispatch_queue_t? = nil, serializer: Serializer, completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Self {
  135. self.delegate.queue.addOperationWithBlock {
  136. let (responseObject: AnyObject?, serializationError: NSError?) = serializer(self.request, self.response, self.delegate.data)
  137. dispatch_async(queue ?? dispatch_get_main_queue()) {
  138. completionHandler(self.request, self.response, responseObject, self.delegate.error ?? serializationError)
  139. }
  140. }
  141. return self
  142. }
  143. // MARK: - State
  144. /**
  145. Suspends the request.
  146. */
  147. public func suspend() {
  148. self.task.suspend()
  149. }
  150. /**
  151. Resumes the request.
  152. */
  153. public func resume() {
  154. self.task.resume()
  155. }
  156. /**
  157. Cancels the request.
  158. */
  159. public func cancel() {
  160. if let
  161. downloadDelegate = delegate as? DownloadTaskDelegate,
  162. downloadTask = downloadDelegate.downloadTask
  163. {
  164. downloadTask.cancelByProducingResumeData { data in
  165. downloadDelegate.resumeData = data
  166. }
  167. } else {
  168. self.task.cancel()
  169. }
  170. }
  171. // MARK: - TaskDelegate
  172. /**
  173. The task delegate is responsible for handling all delegate callbacks for the underlying task as well as
  174. executing all operations attached to the serial operation queue upon task completion.
  175. */
  176. public class TaskDelegate: NSObject {
  177. /// The serial operation queue used to execute all operations after the task completes.
  178. public let queue: NSOperationQueue
  179. let task: NSURLSessionTask
  180. let progress: NSProgress
  181. var data: NSData? { return nil }
  182. var error: NSError?
  183. var credential: NSURLCredential?
  184. init(task: NSURLSessionTask) {
  185. self.task = task
  186. self.progress = NSProgress(totalUnitCount: 0)
  187. self.queue = {
  188. let operationQueue = NSOperationQueue()
  189. operationQueue.maxConcurrentOperationCount = 1
  190. operationQueue.suspended = true
  191. if operationQueue.respondsToSelector("qualityOfService") {
  192. operationQueue.qualityOfService = NSQualityOfService.Utility
  193. }
  194. return operationQueue
  195. }()
  196. }
  197. deinit {
  198. self.queue.cancelAllOperations()
  199. self.queue.suspended = true
  200. }
  201. // MARK: - NSURLSessionTaskDelegate
  202. // MARK: Override Closures
  203. var taskWillPerformHTTPRedirection: ((NSURLSession, NSURLSessionTask, NSHTTPURLResponse, NSURLRequest) -> NSURLRequest?)?
  204. var taskDidReceiveChallenge: ((NSURLSession, NSURLSessionTask, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))?
  205. var taskNeedNewBodyStream: ((NSURLSession, NSURLSessionTask) -> NSInputStream?)?
  206. var taskDidCompleteWithError: ((NSURLSession, NSURLSessionTask, NSError?) -> Void)?
  207. // MARK: Delegate Methods
  208. func URLSession(session: NSURLSession, task: NSURLSessionTask, willPerformHTTPRedirection response: NSHTTPURLResponse, newRequest request: NSURLRequest, completionHandler: ((NSURLRequest!) -> Void)) {
  209. var redirectRequest: NSURLRequest? = request
  210. if let taskWillPerformHTTPRedirection = self.taskWillPerformHTTPRedirection {
  211. redirectRequest = taskWillPerformHTTPRedirection(session, task, response, request)
  212. }
  213. completionHandler(redirectRequest)
  214. }
  215. func URLSession(session: NSURLSession, task: NSURLSessionTask, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential!) -> Void)) {
  216. var disposition: NSURLSessionAuthChallengeDisposition = .PerformDefaultHandling
  217. var credential: NSURLCredential?
  218. if let taskDidReceiveChallenge = self.taskDidReceiveChallenge {
  219. (disposition, credential) = taskDidReceiveChallenge(session, task, challenge)
  220. } else {
  221. if challenge.previousFailureCount > 0 {
  222. disposition = .CancelAuthenticationChallenge
  223. } else {
  224. credential = self.credential ?? session.configuration.URLCredentialStorage?.defaultCredentialForProtectionSpace(challenge.protectionSpace)
  225. if credential != nil {
  226. disposition = .UseCredential
  227. }
  228. }
  229. }
  230. completionHandler(disposition, credential)
  231. }
  232. func URLSession(session: NSURLSession, task: NSURLSessionTask, needNewBodyStream completionHandler: ((NSInputStream!) -> Void)) {
  233. var bodyStream: NSInputStream?
  234. if let taskNeedNewBodyStream = self.taskNeedNewBodyStream {
  235. bodyStream = taskNeedNewBodyStream(session, task)
  236. }
  237. completionHandler(bodyStream)
  238. }
  239. func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) {
  240. if let taskDidCompleteWithError = self.taskDidCompleteWithError {
  241. taskDidCompleteWithError(session, task, error)
  242. } else {
  243. if error != nil {
  244. self.error = error
  245. }
  246. self.queue.suspended = false
  247. }
  248. }
  249. }
  250. // MARK: - DataTaskDelegate
  251. class DataTaskDelegate: TaskDelegate, NSURLSessionDataDelegate {
  252. var dataTask: NSURLSessionDataTask? { return self.task as? NSURLSessionDataTask }
  253. private var totalBytesReceived: Int64 = 0
  254. private var mutableData: NSMutableData
  255. override var data: NSData? {
  256. if self.dataStream != nil {
  257. return nil
  258. } else {
  259. return self.mutableData
  260. }
  261. }
  262. private var expectedContentLength: Int64?
  263. private var dataProgress: ((bytesReceived: Int64, totalBytesReceived: Int64, totalBytesExpectedToReceive: Int64) -> Void)?
  264. private var dataStream: ((data: NSData) -> Void)?
  265. override init(task: NSURLSessionTask) {
  266. self.mutableData = NSMutableData()
  267. super.init(task: task)
  268. }
  269. // MARK: - NSURLSessionDataDelegate
  270. // MARK: Override Closures
  271. var dataTaskDidReceiveResponse: ((NSURLSession, NSURLSessionDataTask, NSURLResponse) -> NSURLSessionResponseDisposition)?
  272. var dataTaskDidBecomeDownloadTask: ((NSURLSession, NSURLSessionDataTask, NSURLSessionDownloadTask) -> Void)?
  273. var dataTaskDidReceiveData: ((NSURLSession, NSURLSessionDataTask, NSData) -> Void)?
  274. var dataTaskWillCacheResponse: ((NSURLSession, NSURLSessionDataTask, NSCachedURLResponse) -> NSCachedURLResponse?)?
  275. // MARK: Delegate Methods
  276. func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveResponse response: NSURLResponse, completionHandler: ((NSURLSessionResponseDisposition) -> Void)) {
  277. var disposition: NSURLSessionResponseDisposition = .Allow
  278. self.expectedContentLength = response.expectedContentLength
  279. if let dataTaskDidReceiveResponse = self.dataTaskDidReceiveResponse {
  280. disposition = dataTaskDidReceiveResponse(session, dataTask, response)
  281. }
  282. completionHandler(disposition)
  283. }
  284. func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didBecomeDownloadTask downloadTask: NSURLSessionDownloadTask) {
  285. self.dataTaskDidBecomeDownloadTask?(session, dataTask, downloadTask)
  286. }
  287. func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) {
  288. if let dataTaskDidReceiveData = self.dataTaskDidReceiveData {
  289. dataTaskDidReceiveData(session, dataTask, data)
  290. } else {
  291. if let dataStream = self.dataStream {
  292. dataStream(data: data)
  293. } else {
  294. self.mutableData.appendData(data)
  295. }
  296. self.totalBytesReceived += data.length
  297. let totalBytesExpectedToReceive = dataTask.response?.expectedContentLength ?? NSURLSessionTransferSizeUnknown
  298. self.progress.totalUnitCount = totalBytesExpectedToReceive
  299. self.progress.completedUnitCount = totalBytesReceived
  300. self.dataProgress?(bytesReceived: Int64(data.length), totalBytesReceived: self.totalBytesReceived, totalBytesExpectedToReceive: totalBytesExpectedToReceive)
  301. }
  302. }
  303. func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, willCacheResponse proposedResponse: NSCachedURLResponse, completionHandler: ((NSCachedURLResponse!) -> Void)) {
  304. var cachedResponse: NSCachedURLResponse? = proposedResponse
  305. if let dataTaskWillCacheResponse = self.dataTaskWillCacheResponse {
  306. cachedResponse = dataTaskWillCacheResponse(session, dataTask, proposedResponse)
  307. }
  308. completionHandler(cachedResponse)
  309. }
  310. }
  311. }
  312. // MARK: - Printable
  313. extension Request: Printable {
  314. /// The textual representation used when written to an output stream, which includes the HTTP method and URL, as well as the response status code if a response has been received.
  315. public var description: String {
  316. var components: [String] = []
  317. if let HTTPMethod = self.request.HTTPMethod {
  318. components.append(HTTPMethod)
  319. }
  320. components.append(self.request.URL!.absoluteString!)
  321. if let response = self.response {
  322. components.append("(\(response.statusCode))")
  323. }
  324. return join(" ", components)
  325. }
  326. }
  327. // MARK: - DebugPrintable
  328. extension Request: DebugPrintable {
  329. func cURLRepresentation() -> String {
  330. var components: [String] = ["$ curl -i"]
  331. let URL = self.request.URL
  332. if let HTTPMethod = self.request.HTTPMethod where HTTPMethod != "GET" {
  333. components.append("-X \(HTTPMethod)")
  334. }
  335. if let credentialStorage = self.session.configuration.URLCredentialStorage {
  336. let protectionSpace = NSURLProtectionSpace(host: URL!.host!, port: URL!.port?.integerValue ?? 0, `protocol`: URL!.scheme!, realm: URL!.host!, authenticationMethod: NSURLAuthenticationMethodHTTPBasic)
  337. if let credentials = credentialStorage.credentialsForProtectionSpace(protectionSpace)?.values.array {
  338. for credential: NSURLCredential in (credentials as! [NSURLCredential]) {
  339. components.append("-u \(credential.user!):\(credential.password!)")
  340. }
  341. } else {
  342. if let credential = self.delegate.credential {
  343. components.append("-u \(credential.user!):\(credential.password!)")
  344. }
  345. }
  346. }
  347. // Temporarily disabled on OS X due to build failure for CocoaPods
  348. // See https://github.com/CocoaPods/swift/issues/24
  349. #if !os(OSX)
  350. if self.session.configuration.HTTPShouldSetCookies {
  351. if let cookieStorage = self.session.configuration.HTTPCookieStorage,
  352. cookies = cookieStorage.cookiesForURL(URL!) as? [NSHTTPCookie]
  353. where !cookies.isEmpty
  354. {
  355. let string = cookies.reduce(""){ $0 + "\($1.name)=\($1.value ?? String());" }
  356. components.append("-b \"\(string.substringToIndex(string.endIndex.predecessor()))\"")
  357. }
  358. }
  359. #endif
  360. if let headerFields = self.request.allHTTPHeaderFields {
  361. for (field, value) in headerFields {
  362. switch field {
  363. case "Cookie":
  364. continue
  365. default:
  366. components.append("-H \"\(field): \(value)\"")
  367. }
  368. }
  369. }
  370. if let additionalHeaders = self.session.configuration.HTTPAdditionalHeaders {
  371. for (field, value) in additionalHeaders {
  372. switch field {
  373. case "Cookie":
  374. continue
  375. default:
  376. components.append("-H \"\(field): \(value)\"")
  377. }
  378. }
  379. }
  380. if let
  381. HTTPBody = self.request.HTTPBody,
  382. escapedBody = NSString(data: HTTPBody, encoding: NSUTF8StringEncoding)?.stringByReplacingOccurrencesOfString("\"", withString: "\\\"")
  383. {
  384. components.append("-d \"\(escapedBody)\"")
  385. }
  386. components.append("\"\(URL!.absoluteString!)\"")
  387. return join(" \\\n\t", components)
  388. }
  389. /// The textual representation used when written to an output stream, in the form of a cURL command.
  390. public var debugDescription: String {
  391. return cURLRepresentation()
  392. }
  393. }