Request.swift 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  1. // Request.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. - parameter user: The user.
  58. - parameter password: The password.
  59. - parameter persistence: The URL credential persistence. `.ForSession` by default.
  60. - returns: The request.
  61. */
  62. public func authenticate(user 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. - parameter credential: The credential.
  69. - returns: The request.
  70. */
  71. public func authenticate(usingCredential credential: NSURLCredential) -> Self {
  72. 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. - parameter 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 = delegate as? UploadTaskDelegate {
  85. uploadDelegate.uploadProgress = closure
  86. } else if let dataDelegate = delegate as? DataTaskDelegate {
  87. dataDelegate.dataProgress = closure
  88. } else if let downloadDelegate = 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. - parameter 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 = delegate as? DataTaskDelegate {
  101. dataDelegate.dataStream = closure
  102. }
  103. return self
  104. }
  105. // MARK: - State
  106. /**
  107. Suspends the request.
  108. */
  109. public func suspend() {
  110. task.suspend()
  111. }
  112. /**
  113. Resumes the request.
  114. */
  115. public func resume() {
  116. task.resume()
  117. }
  118. /**
  119. Cancels the request.
  120. */
  121. public func cancel() {
  122. if let
  123. downloadDelegate = delegate as? DownloadTaskDelegate,
  124. downloadTask = downloadDelegate.downloadTask
  125. {
  126. downloadTask.cancelByProducingResumeData { data in
  127. downloadDelegate.resumeData = data
  128. }
  129. } else {
  130. task.cancel()
  131. }
  132. }
  133. // MARK: - TaskDelegate
  134. /**
  135. The task delegate is responsible for handling all delegate callbacks for the underlying task as well as
  136. executing all operations attached to the serial operation queue upon task completion.
  137. */
  138. public class TaskDelegate: NSObject {
  139. /// The serial operation queue used to execute all operations after the task completes.
  140. public let queue: NSOperationQueue
  141. let task: NSURLSessionTask
  142. let progress: NSProgress
  143. var data: NSData? { return nil }
  144. var error: NSError?
  145. var credential: NSURLCredential?
  146. init(task: NSURLSessionTask) {
  147. self.task = task
  148. self.progress = NSProgress(totalUnitCount: 0)
  149. self.queue = {
  150. let operationQueue = NSOperationQueue()
  151. operationQueue.maxConcurrentOperationCount = 1
  152. operationQueue.suspended = true
  153. if #available(OSX 10.10, *) {
  154. operationQueue.qualityOfService = NSQualityOfService.Utility
  155. }
  156. return operationQueue
  157. }()
  158. }
  159. deinit {
  160. queue.cancelAllOperations()
  161. queue.suspended = true
  162. }
  163. // MARK: - NSURLSessionTaskDelegate
  164. // MARK: Override Closures
  165. var taskWillPerformHTTPRedirection: ((NSURLSession, NSURLSessionTask, NSHTTPURLResponse, NSURLRequest) -> NSURLRequest?)?
  166. var taskDidReceiveChallenge: ((NSURLSession, NSURLSessionTask, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))?
  167. var taskNeedNewBodyStream: ((NSURLSession, NSURLSessionTask) -> NSInputStream?)?
  168. var taskDidCompleteWithError: ((NSURLSession, NSURLSessionTask, NSError?) -> Void)?
  169. // MARK: Delegate Methods
  170. func URLSession(session: NSURLSession, task: NSURLSessionTask, willPerformHTTPRedirection response: NSHTTPURLResponse, newRequest request: NSURLRequest, completionHandler: ((NSURLRequest?) -> Void)) {
  171. var redirectRequest: NSURLRequest? = request
  172. if let taskWillPerformHTTPRedirection = taskWillPerformHTTPRedirection {
  173. redirectRequest = taskWillPerformHTTPRedirection(session, task, response, request)
  174. }
  175. completionHandler(redirectRequest)
  176. }
  177. func URLSession(session: NSURLSession, task: NSURLSessionTask, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void)) {
  178. var disposition: NSURLSessionAuthChallengeDisposition = .PerformDefaultHandling
  179. var credential: NSURLCredential?
  180. if let taskDidReceiveChallenge = taskDidReceiveChallenge {
  181. (disposition, credential) = taskDidReceiveChallenge(session, task, challenge)
  182. } else if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
  183. let host = challenge.protectionSpace.host
  184. if let
  185. serverTrustPolicy = session.serverTrustPolicyManager?.serverTrustPolicyForHost(host),
  186. serverTrust = challenge.protectionSpace.serverTrust
  187. {
  188. if serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host) {
  189. disposition = .UseCredential
  190. credential = NSURLCredential(forTrust: serverTrust)
  191. } else {
  192. disposition = .CancelAuthenticationChallenge
  193. }
  194. }
  195. } else {
  196. if challenge.previousFailureCount > 0 {
  197. disposition = .CancelAuthenticationChallenge
  198. } else {
  199. credential = self.credential ?? session.configuration.URLCredentialStorage?.defaultCredentialForProtectionSpace(challenge.protectionSpace)
  200. if credential != nil {
  201. disposition = .UseCredential
  202. }
  203. }
  204. }
  205. completionHandler(disposition, credential)
  206. }
  207. func URLSession(session: NSURLSession, task: NSURLSessionTask, needNewBodyStream completionHandler: ((NSInputStream?) -> Void)) {
  208. var bodyStream: NSInputStream?
  209. if let taskNeedNewBodyStream = taskNeedNewBodyStream {
  210. bodyStream = taskNeedNewBodyStream(session, task)
  211. }
  212. completionHandler(bodyStream)
  213. }
  214. func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) {
  215. if let taskDidCompleteWithError = taskDidCompleteWithError {
  216. taskDidCompleteWithError(session, task, error)
  217. } else {
  218. if let error = error {
  219. self.error = error
  220. if let
  221. downloadDelegate = self as? DownloadTaskDelegate,
  222. userInfo = error.userInfo as? [String: AnyObject],
  223. resumeData = userInfo[NSURLSessionDownloadTaskResumeData] as? NSData
  224. {
  225. downloadDelegate.resumeData = resumeData
  226. }
  227. }
  228. queue.suspended = false
  229. }
  230. }
  231. }
  232. // MARK: - DataTaskDelegate
  233. class DataTaskDelegate: TaskDelegate, NSURLSessionDataDelegate {
  234. var dataTask: NSURLSessionDataTask? { return task as? NSURLSessionDataTask }
  235. private var totalBytesReceived: Int64 = 0
  236. private var mutableData: NSMutableData
  237. override var data: NSData? {
  238. if dataStream != nil {
  239. return nil
  240. } else {
  241. return mutableData
  242. }
  243. }
  244. private var expectedContentLength: Int64?
  245. private var dataProgress: ((bytesReceived: Int64, totalBytesReceived: Int64, totalBytesExpectedToReceive: Int64) -> Void)?
  246. private var dataStream: ((data: NSData) -> Void)?
  247. override init(task: NSURLSessionTask) {
  248. mutableData = NSMutableData()
  249. super.init(task: task)
  250. }
  251. // MARK: - NSURLSessionDataDelegate
  252. // MARK: Override Closures
  253. var dataTaskDidReceiveResponse: ((NSURLSession, NSURLSessionDataTask, NSURLResponse) -> NSURLSessionResponseDisposition)?
  254. var dataTaskDidBecomeDownloadTask: ((NSURLSession, NSURLSessionDataTask, NSURLSessionDownloadTask) -> Void)?
  255. var dataTaskDidReceiveData: ((NSURLSession, NSURLSessionDataTask, NSData) -> Void)?
  256. var dataTaskWillCacheResponse: ((NSURLSession, NSURLSessionDataTask, NSCachedURLResponse) -> NSCachedURLResponse?)?
  257. // MARK: Delegate Methods
  258. func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveResponse response: NSURLResponse, completionHandler: ((NSURLSessionResponseDisposition) -> Void)) {
  259. var disposition: NSURLSessionResponseDisposition = .Allow
  260. expectedContentLength = response.expectedContentLength
  261. if let dataTaskDidReceiveResponse = dataTaskDidReceiveResponse {
  262. disposition = dataTaskDidReceiveResponse(session, dataTask, response)
  263. }
  264. completionHandler(disposition)
  265. }
  266. func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didBecomeDownloadTask downloadTask: NSURLSessionDownloadTask) {
  267. dataTaskDidBecomeDownloadTask?(session, dataTask, downloadTask)
  268. }
  269. func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) {
  270. if let dataTaskDidReceiveData = dataTaskDidReceiveData {
  271. dataTaskDidReceiveData(session, dataTask, data)
  272. } else {
  273. if let dataStream = dataStream {
  274. dataStream(data: data)
  275. } else {
  276. mutableData.appendData(data)
  277. }
  278. totalBytesReceived += data.length
  279. let totalBytesExpectedToReceive = dataTask.response?.expectedContentLength ?? NSURLSessionTransferSizeUnknown
  280. progress.totalUnitCount = totalBytesExpectedToReceive
  281. progress.completedUnitCount = totalBytesReceived
  282. dataProgress?(bytesReceived: Int64(data.length), totalBytesReceived: totalBytesReceived, totalBytesExpectedToReceive: totalBytesExpectedToReceive)
  283. }
  284. }
  285. func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, willCacheResponse proposedResponse: NSCachedURLResponse, completionHandler: ((NSCachedURLResponse?) -> Void)) {
  286. var cachedResponse: NSCachedURLResponse? = proposedResponse
  287. if let dataTaskWillCacheResponse = dataTaskWillCacheResponse {
  288. cachedResponse = dataTaskWillCacheResponse(session, dataTask, proposedResponse)
  289. }
  290. completionHandler(cachedResponse)
  291. }
  292. }
  293. }
  294. // MARK: - CustomStringConvertible
  295. extension Request: CustomStringConvertible {
  296. /// 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.
  297. public var description: String {
  298. var components: [String] = []
  299. if let HTTPMethod = request?.HTTPMethod {
  300. components.append(HTTPMethod)
  301. }
  302. if let URLString = request?.URL?.absoluteString {
  303. components.append(URLString)
  304. }
  305. if let response = response {
  306. components.append("(\(response.statusCode))")
  307. }
  308. return " ".join(components)
  309. }
  310. }
  311. // MARK: - CustomDebugStringConvertible
  312. extension Request: CustomDebugStringConvertible {
  313. func cURLRepresentation() -> String {
  314. var components = ["$ curl -i"]
  315. guard let request = self.request else {
  316. return "$ curl command could not be created"
  317. }
  318. let URL = request.URL
  319. if let HTTPMethod = request.HTTPMethod where HTTPMethod != "GET" {
  320. components.append("-X \(HTTPMethod)")
  321. }
  322. if let credentialStorage = self.session.configuration.URLCredentialStorage {
  323. let protectionSpace = NSURLProtectionSpace(
  324. host: URL!.host!,
  325. port: URL!.port?.integerValue ?? 0,
  326. `protocol`: URL!.scheme,
  327. realm: URL!.host!,
  328. authenticationMethod: NSURLAuthenticationMethodHTTPBasic
  329. )
  330. if let credentials = credentialStorage.credentialsForProtectionSpace(protectionSpace)?.values.array {
  331. for credential in credentials {
  332. components.append("-u \(credential.user!):\(credential.password!)")
  333. }
  334. } else {
  335. if let credential = delegate.credential {
  336. components.append("-u \(credential.user!):\(credential.password!)")
  337. }
  338. }
  339. }
  340. if session.configuration.HTTPShouldSetCookies {
  341. if let
  342. cookieStorage = session.configuration.HTTPCookieStorage,
  343. cookies = cookieStorage.cookiesForURL(URL!) where !cookies.isEmpty
  344. {
  345. let string = cookies.reduce("") { $0 + "\($1.name)=\($1.value ?? String());" }
  346. components.append("-b \"\(string.substringToIndex(string.endIndex.predecessor()))\"")
  347. }
  348. }
  349. if let headerFields = request.allHTTPHeaderFields {
  350. for (field, value) in headerFields {
  351. switch field {
  352. case "Cookie":
  353. continue
  354. default:
  355. components.append("-H \"\(field): \(value)\"")
  356. }
  357. }
  358. }
  359. if let additionalHeaders = session.configuration.HTTPAdditionalHeaders {
  360. for (field, value) in additionalHeaders {
  361. switch field {
  362. case "Cookie":
  363. continue
  364. default:
  365. components.append("-H \"\(field): \(value)\"")
  366. }
  367. }
  368. }
  369. if let
  370. HTTPBody = request.HTTPBody,
  371. escapedBody = NSString(data: HTTPBody, encoding: NSUTF8StringEncoding)?.stringByReplacingOccurrencesOfString("\"", withString: "\\\"")
  372. {
  373. components.append("-d \"\(escapedBody)\"")
  374. }
  375. components.append("\"\(URL!.absoluteString)\"")
  376. return " \\\n\t".join(components)
  377. }
  378. /// The textual representation used when written to an output stream, in the form of a cURL command.
  379. public var debugDescription: String {
  380. return cURLRepresentation()
  381. }
  382. }