2
0

Request.swift 18 KB

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