Request.swift 20 KB

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