Request.swift 20 KB

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