Request.swift 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582
  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: URLSessionTask { return delegate.task }
  35. /// The session belonging to the underlying task.
  36. public let session: URLSession
  37. /// The request sent or to be sent to the server.
  38. public var request: Foundation.URLRequest? { return task.originalRequest }
  39. /// The response received from the server, if any.
  40. public var response: HTTPURLResponse? { return task.response as? HTTPURLResponse }
  41. /// The progress of the request lifecycle.
  42. public var progress: Progress { return delegate.progress }
  43. var startTime: CFAbsoluteTime?
  44. var endTime: CFAbsoluteTime?
  45. // MARK: - Lifecycle
  46. init(session: URLSession, task: URLSessionTask) {
  47. self.session = session
  48. switch task {
  49. case is URLSessionUploadTask:
  50. delegate = UploadTaskDelegate(task: task)
  51. case is URLSessionDataTask:
  52. delegate = DataTaskDelegate(task: task)
  53. case is URLSessionDownloadTask:
  54. delegate = DownloadTaskDelegate(task: task)
  55. default:
  56. delegate = TaskDelegate(task: task)
  57. }
  58. delegate.queue.addOperation { 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. @discardableResult
  69. public func authenticate(
  70. user: String,
  71. password: String,
  72. persistence: URLCredential.Persistence = .forSession)
  73. -> Self
  74. {
  75. let credential = URLCredential(user: user, password: password, persistence: persistence)
  76. return authenticate(usingCredential: credential)
  77. }
  78. /**
  79. Associates a specified credential with the request.
  80. - parameter credential: The credential.
  81. - returns: The request.
  82. */
  83. @discardableResult
  84. public func authenticate(usingCredential credential: URLCredential) -> Self {
  85. delegate.credential = credential
  86. return self
  87. }
  88. /**
  89. Returns a base64 encoded basic authentication credential as an authorization header dictionary.
  90. - parameter user: The user.
  91. - parameter password: The password.
  92. - returns: A dictionary with Authorization key and credential value or empty dictionary if encoding fails.
  93. */
  94. public static func authorizationHeader(user: String, password: String) -> [String: String] {
  95. guard let data = "\(user):\(password)".data(using: String.Encoding.utf8) else { return [:] }
  96. let credential = data.base64EncodedString(options: [])
  97. return ["Authorization": "Basic \(credential)"]
  98. }
  99. // MARK: - Progress
  100. /**
  101. Sets a closure to be called periodically during the lifecycle of the request as data is written to or read
  102. from the server.
  103. - For uploads, the progress closure returns the bytes written, total bytes written, and total bytes expected
  104. to write.
  105. - For downloads and data tasks, the progress closure returns the bytes read, total bytes read, and total bytes
  106. expected to read.
  107. - parameter closure: The code to be executed periodically during the lifecycle of the request.
  108. - returns: The request.
  109. */
  110. @discardableResult
  111. public func progress(_ closure: ((Int64, Int64, Int64) -> Void)? = nil) -> Self {
  112. if let uploadDelegate = delegate as? UploadTaskDelegate {
  113. uploadDelegate.uploadProgress = closure
  114. } else if let dataDelegate = delegate as? DataTaskDelegate {
  115. dataDelegate.dataProgress = closure
  116. } else if let downloadDelegate = delegate as? DownloadTaskDelegate {
  117. downloadDelegate.downloadProgress = closure
  118. }
  119. return self
  120. }
  121. /**
  122. Sets a closure to be called periodically during the lifecycle of the request as data is read from the server.
  123. This closure returns the bytes most recently received from the server, not including data from previous calls.
  124. If this closure is set, data will only be available within this closure, and will not be saved elsewhere. It is
  125. also important to note that the `response` closure will be called with nil `responseData`.
  126. - parameter closure: The code to be executed periodically during the lifecycle of the request.
  127. - returns: The request.
  128. */
  129. @discardableResult
  130. public func stream(_ closure: ((Data) -> Void)? = nil) -> Self {
  131. if let dataDelegate = delegate as? DataTaskDelegate {
  132. dataDelegate.dataStream = closure
  133. }
  134. return self
  135. }
  136. // MARK: - State
  137. /**
  138. Resumes the request.
  139. */
  140. public func resume() {
  141. if startTime == nil { startTime = CFAbsoluteTimeGetCurrent() }
  142. task.resume()
  143. NotificationCenter.default.post(
  144. name: Notification.Name.Task.DidResume,
  145. object: self,
  146. userInfo: [Notification.Key.Task: task]
  147. )
  148. }
  149. /**
  150. Suspends the request.
  151. */
  152. public func suspend() {
  153. task.suspend()
  154. NotificationCenter.default.post(
  155. name: Notification.Name.Task.DidSuspend,
  156. object: self,
  157. userInfo: [Notification.Key.Task: task]
  158. )
  159. }
  160. /**
  161. Cancels the request.
  162. */
  163. public func cancel() {
  164. if let downloadDelegate = delegate as? DownloadTaskDelegate,
  165. let downloadTask = downloadDelegate.downloadTask
  166. {
  167. downloadTask.cancel { data in
  168. downloadDelegate.resumeData = data
  169. }
  170. } else {
  171. task.cancel()
  172. }
  173. NotificationCenter.default.post(
  174. name: Notification.Name.Task.DidCancel,
  175. object: self,
  176. userInfo: [Notification.Key.Task: task]
  177. )
  178. }
  179. // MARK: - TaskDelegate
  180. /**
  181. The task delegate is responsible for handling all delegate callbacks for the underlying task as well as
  182. executing all operations attached to the serial operation queue upon task completion.
  183. */
  184. public class TaskDelegate: NSObject {
  185. /// The serial operation queue used to execute all operations after the task completes.
  186. public let queue: OperationQueue
  187. let task: URLSessionTask
  188. let progress: Progress
  189. var data: Data? { return nil }
  190. var error: NSError?
  191. var initialResponseTime: CFAbsoluteTime?
  192. var credential: URLCredential?
  193. init(task: URLSessionTask) {
  194. self.task = task
  195. self.progress = Progress(totalUnitCount: 0)
  196. self.queue = {
  197. let operationQueue = OperationQueue()
  198. operationQueue.maxConcurrentOperationCount = 1
  199. operationQueue.isSuspended = true
  200. operationQueue.qualityOfService = .utility
  201. return operationQueue
  202. }()
  203. }
  204. deinit {
  205. queue.cancelAllOperations()
  206. queue.isSuspended = false
  207. }
  208. // MARK: - NSURLSessionTaskDelegate
  209. // MARK: Override Closures
  210. var taskWillPerformHTTPRedirection: ((Foundation.URLSession, URLSessionTask, HTTPURLResponse, Foundation.URLRequest) -> Foundation.URLRequest?)?
  211. var taskDidReceiveChallenge: ((Foundation.URLSession, URLSessionTask, URLAuthenticationChallenge) -> (Foundation.URLSession.AuthChallengeDisposition, URLCredential?))?
  212. var taskNeedNewBodyStream: ((Foundation.URLSession, URLSessionTask) -> InputStream?)?
  213. var taskDidCompleteWithError: ((Foundation.URLSession, URLSessionTask, NSError?) -> Void)?
  214. // MARK: Delegate Methods
  215. // RDAR
  216. @objc(URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:)
  217. func urlSession(
  218. _ session: Foundation.URLSession,
  219. task: URLSessionTask,
  220. willPerformHTTPRedirection response: HTTPURLResponse,
  221. newRequest request: Foundation.URLRequest,
  222. completionHandler: ((Foundation.URLRequest?) -> Void))
  223. {
  224. var redirectRequest: Foundation.URLRequest? = request
  225. if let taskWillPerformHTTPRedirection = taskWillPerformHTTPRedirection {
  226. redirectRequest = taskWillPerformHTTPRedirection(session, task, response, request)
  227. }
  228. completionHandler(redirectRequest)
  229. }
  230. @objc(URLSession:task:didReceiveChallenge:completionHandler:)
  231. func urlSession(
  232. _ session: Foundation.URLSession,
  233. task: URLSessionTask,
  234. didReceive challenge: URLAuthenticationChallenge,
  235. completionHandler: ((Foundation.URLSession.AuthChallengeDisposition, URLCredential?) -> Void))
  236. {
  237. var disposition: Foundation.URLSession.AuthChallengeDisposition = .performDefaultHandling
  238. var credential: URLCredential?
  239. if let taskDidReceiveChallenge = taskDidReceiveChallenge {
  240. (disposition, credential) = taskDidReceiveChallenge(session, task, challenge)
  241. } else if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
  242. let host = challenge.protectionSpace.host
  243. if let serverTrustPolicy = session.serverTrustPolicyManager?.serverTrustPolicyForHost(host),
  244. let serverTrust = challenge.protectionSpace.serverTrust
  245. {
  246. if serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host) {
  247. disposition = .useCredential
  248. credential = URLCredential(trust: serverTrust)
  249. } else {
  250. disposition = .cancelAuthenticationChallenge
  251. }
  252. }
  253. } else {
  254. if challenge.previousFailureCount > 0 {
  255. disposition = .rejectProtectionSpace
  256. } else {
  257. credential = self.credential ?? session.configuration.urlCredentialStorage?.defaultCredential(for: challenge.protectionSpace)
  258. if credential != nil {
  259. disposition = .useCredential
  260. }
  261. }
  262. }
  263. completionHandler(disposition, credential)
  264. }
  265. @objc(URLSession:task:needNewBodyStream:)
  266. func urlSession(
  267. _ session: Foundation.URLSession,
  268. task: URLSessionTask,
  269. needNewBodyStream completionHandler: ((InputStream?) -> Void))
  270. {
  271. var bodyStream: InputStream?
  272. if let taskNeedNewBodyStream = taskNeedNewBodyStream {
  273. bodyStream = taskNeedNewBodyStream(session, task)
  274. }
  275. completionHandler(bodyStream)
  276. }
  277. @objc(URLSession:task:didCompleteWithError:)
  278. func urlSession(_ session: Foundation.URLSession, task: URLSessionTask, didCompleteWithError error: NSError?) {
  279. if let taskDidCompleteWithError = taskDidCompleteWithError {
  280. taskDidCompleteWithError(session, task, error)
  281. } else {
  282. if let error = error {
  283. self.error = error
  284. if let downloadDelegate = self as? DownloadTaskDelegate,
  285. let userInfo = error.userInfo as? [String: AnyObject],
  286. let resumeData = userInfo[NSURLSessionDownloadTaskResumeData] as? Data
  287. {
  288. downloadDelegate.resumeData = resumeData
  289. }
  290. }
  291. queue.isSuspended = false
  292. }
  293. }
  294. }
  295. // MARK: - DataTaskDelegate
  296. class DataTaskDelegate: TaskDelegate, URLSessionDataDelegate {
  297. var dataTask: URLSessionDataTask? { return task as? URLSessionDataTask }
  298. private var totalBytesReceived: Int64 = 0
  299. private var mutableData: NSMutableData
  300. override var data: Data? {
  301. if dataStream != nil {
  302. return nil
  303. } else {
  304. return mutableData as Data
  305. }
  306. }
  307. private var expectedContentLength: Int64?
  308. private var dataProgress: ((bytesReceived: Int64, totalBytesReceived: Int64, totalBytesExpectedToReceive: Int64) -> Void)?
  309. private var dataStream: ((data: Data) -> Void)?
  310. override init(task: URLSessionTask) {
  311. mutableData = NSMutableData()
  312. super.init(task: task)
  313. }
  314. // MARK: - NSURLSessionDataDelegate
  315. // MARK: Override Closures
  316. var dataTaskDidReceiveResponse: ((Foundation.URLSession, URLSessionDataTask, URLResponse) -> Foundation.URLSession.ResponseDisposition)?
  317. var dataTaskDidBecomeDownloadTask: ((Foundation.URLSession, URLSessionDataTask, URLSessionDownloadTask) -> Void)?
  318. var dataTaskDidReceiveData: ((Foundation.URLSession, URLSessionDataTask, Data) -> Void)?
  319. var dataTaskWillCacheResponse: ((Foundation.URLSession, URLSessionDataTask, CachedURLResponse) -> CachedURLResponse?)?
  320. // MARK: Delegate Methods
  321. func urlSession(
  322. _ session: URLSession,
  323. dataTask: URLSessionDataTask,
  324. didReceive response: URLResponse,
  325. completionHandler: ((Foundation.URLSession.ResponseDisposition) -> Void))
  326. {
  327. var disposition: Foundation.URLSession.ResponseDisposition = .allow
  328. expectedContentLength = response.expectedContentLength
  329. if let dataTaskDidReceiveResponse = dataTaskDidReceiveResponse {
  330. disposition = dataTaskDidReceiveResponse(session, dataTask, response)
  331. }
  332. completionHandler(disposition)
  333. }
  334. func urlSession(
  335. _ session: URLSession,
  336. dataTask: URLSessionDataTask,
  337. didBecome downloadTask: URLSessionDownloadTask)
  338. {
  339. dataTaskDidBecomeDownloadTask?(session, dataTask, downloadTask)
  340. }
  341. func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
  342. if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() }
  343. if let dataTaskDidReceiveData = dataTaskDidReceiveData {
  344. dataTaskDidReceiveData(session, dataTask, data)
  345. } else {
  346. if let dataStream = dataStream {
  347. dataStream(data: data)
  348. } else {
  349. mutableData.append(data)
  350. }
  351. totalBytesReceived += data.count
  352. let totalBytesExpected = dataTask.response?.expectedContentLength ?? NSURLSessionTransferSizeUnknown
  353. progress.totalUnitCount = totalBytesExpected
  354. progress.completedUnitCount = totalBytesReceived
  355. dataProgress?(
  356. bytesReceived: Int64(data.count),
  357. totalBytesReceived: totalBytesReceived,
  358. totalBytesExpectedToReceive: totalBytesExpected
  359. )
  360. }
  361. }
  362. func urlSession(
  363. _ session: URLSession,
  364. dataTask: URLSessionDataTask,
  365. willCacheResponse proposedResponse: CachedURLResponse,
  366. completionHandler: ((CachedURLResponse?) -> Void))
  367. {
  368. var cachedResponse: CachedURLResponse? = proposedResponse
  369. if let dataTaskWillCacheResponse = dataTaskWillCacheResponse {
  370. cachedResponse = dataTaskWillCacheResponse(session, dataTask, proposedResponse)
  371. }
  372. completionHandler(cachedResponse)
  373. }
  374. }
  375. }
  376. // MARK: - CustomStringConvertible
  377. extension Request: CustomStringConvertible {
  378. /**
  379. The textual representation used when written to an output stream, which includes the HTTP method and URL, as
  380. well as the response status code if a response has been received.
  381. */
  382. public var description: String {
  383. var components: [String] = []
  384. if let HTTPMethod = request?.httpMethod {
  385. components.append(HTTPMethod)
  386. }
  387. if let URLString = request?.url?.absoluteString {
  388. components.append(URLString)
  389. }
  390. if let response = response {
  391. components.append("(\(response.statusCode))")
  392. }
  393. return components.joined(separator: " ")
  394. }
  395. }
  396. // MARK: - CustomDebugStringConvertible
  397. extension Request: CustomDebugStringConvertible {
  398. func cURLRepresentation() -> String {
  399. var components = ["$ curl -i"]
  400. guard let request = self.request,
  401. let URL = request.url,
  402. let host = URL.host
  403. else {
  404. return "$ curl command could not be created"
  405. }
  406. if let httpMethod = request.httpMethod, httpMethod != "GET" {
  407. components.append("-X \(httpMethod)")
  408. }
  409. if let credentialStorage = self.session.configuration.urlCredentialStorage {
  410. let protectionSpace = URLProtectionSpace(
  411. host: host,
  412. port: (URL as NSURL).port?.intValue ?? 0,
  413. protocol: URL.scheme,
  414. realm: host,
  415. authenticationMethod: NSURLAuthenticationMethodHTTPBasic
  416. )
  417. if let credentials = credentialStorage.credentials(for: protectionSpace)?.values {
  418. for credential in credentials {
  419. components.append("-u \(credential.user!):\(credential.password!)")
  420. }
  421. } else {
  422. if let credential = delegate.credential {
  423. components.append("-u \(credential.user!):\(credential.password!)")
  424. }
  425. }
  426. }
  427. if session.configuration.httpShouldSetCookies {
  428. if let cookieStorage = session.configuration.httpCookieStorage,
  429. let cookies = cookieStorage.cookies(for: URL), !cookies.isEmpty
  430. {
  431. let string = cookies.reduce("") { $0 + "\($1.name)=\($1.value ?? String());" }
  432. components.append("-b \"\(string.substring(to: string.characters.index(before: string.endIndex)))\"")
  433. }
  434. }
  435. var headers: [NSObject: AnyObject] = [:]
  436. if let additionalHeaders = session.configuration.httpAdditionalHeaders {
  437. for (field, value) in additionalHeaders where field != "Cookie" {
  438. headers[field] = value
  439. }
  440. }
  441. if let headerFields = request.allHTTPHeaderFields {
  442. for (field, value) in headerFields where field != "Cookie" {
  443. headers[field] = value
  444. }
  445. }
  446. for (field, value) in headers {
  447. components.append("-H \"\(field): \(value)\"")
  448. }
  449. if let httpBodyData = request.httpBody,
  450. let httpBody = String(data: httpBodyData, encoding: String.Encoding.utf8)
  451. {
  452. var escapedBody = httpBody.replacingOccurrences(of: "\\\"", with: "\\\\\"")
  453. escapedBody = escapedBody.replacingOccurrences(of: "\"", with: "\\\"")
  454. components.append("-d \"\(escapedBody)\"")
  455. }
  456. components.append("\"\(URL.absoluteString!)\"")
  457. return components.joined(separator: " \\\n\t")
  458. }
  459. /// The textual representation used when written to an output stream, in the form of a cURL command.
  460. public var debugDescription: String {
  461. return cURLRepresentation()
  462. }
  463. }