Request.swift 20 KB

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