SessionDelegate.swift 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681
  1. //
  2. // SessionDelegate.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. /// Responsible for handling all delegate callbacks for the underlying session.
  26. open class SessionDelegate: NSObject {
  27. // MARK: URLSessionDelegate Overrides
  28. /// Overrides default behavior for URLSessionDelegate method `urlSession(_:didBecomeInvalidWithError:)`.
  29. open var sessionDidBecomeInvalidWithError: ((URLSession, Error?) -> Void)?
  30. /// Overrides default behavior for URLSessionDelegate method `urlSession(_:didReceive:completionHandler:)`.
  31. open var sessionDidReceiveChallenge: ((URLSession, URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?))?
  32. /// Overrides all behavior for URLSessionDelegate method `urlSession(_:didReceive:completionHandler:)` and requires the caller to call the `completionHandler`.
  33. open var sessionDidReceiveChallengeWithCompletion: ((URLSession, URLAuthenticationChallenge, (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) -> Void)?
  34. /// Overrides default behavior for URLSessionDelegate method `urlSessionDidFinishEvents(forBackgroundURLSession:)`.
  35. open var sessionDidFinishEventsForBackgroundURLSession: ((URLSession) -> Void)?
  36. // MARK: URLSessionTaskDelegate Overrides
  37. /// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)`.
  38. open var taskWillPerformHTTPRedirection: ((URLSession, URLSessionTask, HTTPURLResponse, URLRequest) -> URLRequest?)?
  39. /// Overrides all behavior for URLSessionTaskDelegate method `urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)` and
  40. /// requires the caller to call the `completionHandler`.
  41. open var taskWillPerformHTTPRedirectionWithCompletion: ((URLSession, URLSessionTask, HTTPURLResponse, URLRequest, (URLRequest?) -> Void) -> Void)?
  42. /// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:didReceive:completionHandler:)`.
  43. open var taskDidReceiveChallenge: ((URLSession, URLSessionTask, URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?))?
  44. /// Overrides all behavior for URLSessionTaskDelegate method `urlSession(_:task:didReceive:completionHandler:)` and
  45. /// requires the caller to call the `completionHandler`.
  46. open var taskDidReceiveChallengeWithCompletion: ((URLSession, URLSessionTask, URLAuthenticationChallenge, (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) -> Void)?
  47. /// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:needNewBodyStream:)`.
  48. open var taskNeedNewBodyStream: ((URLSession, URLSessionTask) -> InputStream?)?
  49. /// Overrides all behavior for URLSessionTaskDelegate method `urlSession(_:task:needNewBodyStream:)` and
  50. /// requires the caller to call the `completionHandler`.
  51. open var taskNeedNewBodyStreamWithCompletion: ((URLSession, URLSessionTask, (InputStream?) -> Void) -> Void)?
  52. /// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:)`.
  53. open var taskDidSendBodyData: ((URLSession, URLSessionTask, Int64, Int64, Int64) -> Void)?
  54. /// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:didCompleteWithError:)`.
  55. open var taskDidComplete: ((URLSession, URLSessionTask, Error?) -> Void)?
  56. // MARK: URLSessionDataDelegate Overrides
  57. /// Overrides default behavior for URLSessionDataDelegate method `urlSession(_:dataTask:didReceive:completionHandler:)`.
  58. open var dataTaskDidReceiveResponse: ((URLSession, URLSessionDataTask, URLResponse) -> URLSession.ResponseDisposition)?
  59. /// Overrides all behavior for URLSessionDataDelegate method `urlSession(_:dataTask:didReceive:completionHandler:)` and
  60. /// requires caller to call the `completionHandler`.
  61. open var dataTaskDidReceiveResponseWithCompletion: ((URLSession, URLSessionDataTask, URLResponse, (URLSession.ResponseDisposition) -> Void) -> Void)?
  62. /// Overrides default behavior for URLSessionDataDelegate method `urlSession(_:dataTask:didBecome:)`.
  63. open var dataTaskDidBecomeDownloadTask: ((URLSession, URLSessionDataTask, URLSessionDownloadTask) -> Void)?
  64. /// Overrides default behavior for URLSessionDataDelegate method `urlSession(_:dataTask:didReceive:)`.
  65. open var dataTaskDidReceiveData: ((URLSession, URLSessionDataTask, Data) -> Void)?
  66. /// Overrides default behavior for URLSessionDataDelegate method `urlSession(_:dataTask:willCacheResponse:completionHandler:)`.
  67. open var dataTaskWillCacheResponse: ((URLSession, URLSessionDataTask, CachedURLResponse) -> CachedURLResponse?)?
  68. /// Overrides all behavior for URLSessionDataDelegate method `urlSession(_:dataTask:willCacheResponse:completionHandler:)` and
  69. /// requires caller to call the `completionHandler`.
  70. open var dataTaskWillCacheResponseWithCompletion: ((URLSession, URLSessionDataTask, CachedURLResponse, (CachedURLResponse?) -> Void) -> Void)?
  71. // MARK: URLSessionDownloadDelegate Overrides
  72. /// Overrides default behavior for URLSessionDownloadDelegate method `urlSession(_:downloadTask:didFinishDownloadingTo:)`.
  73. open var downloadTaskDidFinishDownloadingToURL: ((URLSession, URLSessionDownloadTask, URL) -> Void)?
  74. /// Overrides default behavior for URLSessionDownloadDelegate method `urlSession(_:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:)`.
  75. open var downloadTaskDidWriteData: ((URLSession, URLSessionDownloadTask, Int64, Int64, Int64) -> Void)?
  76. /// Overrides default behavior for URLSessionDownloadDelegate method `urlSession(_:downloadTask:didResumeAtOffset:expectedTotalBytes:)`.
  77. open var downloadTaskDidResumeAtOffset: ((URLSession, URLSessionDownloadTask, Int64, Int64) -> Void)?
  78. // MARK: URLSessionStreamDelegate Overrides
  79. #if !os(watchOS)
  80. /// Overrides default behavior for URLSessionStreamDelegate method `urlSession(_:readClosedFor:)`.
  81. open var streamTaskReadClosed: ((URLSession, URLSessionStreamTask) -> Void)?
  82. /// Overrides default behavior for URLSessionStreamDelegate method `urlSession(_:writeClosedFor:)`.
  83. open var streamTaskWriteClosed: ((URLSession, URLSessionStreamTask) -> Void)?
  84. /// Overrides default behavior for URLSessionStreamDelegate method `urlSession(_:betterRouteDiscoveredFor:)`.
  85. open var streamTaskBetterRouteDiscovered: ((URLSession, URLSessionStreamTask) -> Void)?
  86. /// Overrides default behavior for URLSessionStreamDelegate method `urlSession(_:streamTask:didBecome:outputStream:)`.
  87. open var streamTaskDidBecomeInputAndOutputStreams: ((URLSession, URLSessionStreamTask, InputStream, OutputStream) -> Void)?
  88. #endif
  89. // MARK: Properties
  90. var retrier: RequestRetrier?
  91. weak var sessionManager: SessionManager?
  92. private var requests: [Int: Request] = [:]
  93. private let lock = NSLock()
  94. /// Access the task delegate for the specified task in a thread-safe manner.
  95. open subscript(task: URLSessionTask) -> Request? {
  96. get {
  97. lock.lock() ; defer { lock.unlock() }
  98. return requests[task.taskIdentifier]
  99. }
  100. set {
  101. lock.lock() ; defer { lock.unlock() }
  102. requests[task.taskIdentifier] = newValue
  103. }
  104. }
  105. // MARK: Lifecycle
  106. /// Initializes the `SessionDelegate` instance.
  107. ///
  108. /// - returns: The new `SessionDelegate` instance.
  109. public override init() {
  110. super.init()
  111. }
  112. // MARK: NSObject Overrides
  113. /// Returns a `Bool` indicating whether the `SessionDelegate` implements or inherits a method that can respond
  114. /// to a specified message.
  115. ///
  116. /// - parameter selector: A selector that identifies a message.
  117. ///
  118. /// - returns: `true` if the receiver implements or inherits a method that can respond to selector, otherwise `false`.
  119. open override func responds(to selector: Selector) -> Bool {
  120. #if !os(OSX)
  121. if selector == #selector(URLSessionDelegate.urlSessionDidFinishEvents(forBackgroundURLSession:)) {
  122. return sessionDidFinishEventsForBackgroundURLSession != nil
  123. }
  124. #endif
  125. #if !os(watchOS)
  126. switch selector {
  127. case #selector(URLSessionStreamDelegate.urlSession(_:readClosedFor:)):
  128. return streamTaskReadClosed != nil
  129. case #selector(URLSessionStreamDelegate.urlSession(_:writeClosedFor:)):
  130. return streamTaskWriteClosed != nil
  131. case #selector(URLSessionStreamDelegate.urlSession(_:betterRouteDiscoveredFor:)):
  132. return streamTaskBetterRouteDiscovered != nil
  133. case #selector(URLSessionStreamDelegate.urlSession(_:streamTask:didBecome:outputStream:)):
  134. return streamTaskDidBecomeInputAndOutputStreams != nil
  135. default:
  136. break
  137. }
  138. #endif
  139. switch selector {
  140. case #selector(URLSessionDelegate.urlSession(_:didBecomeInvalidWithError:)):
  141. return sessionDidBecomeInvalidWithError != nil
  142. case #selector(URLSessionDelegate.urlSession(_:didReceive:completionHandler:)):
  143. return (sessionDidReceiveChallenge != nil || sessionDidReceiveChallengeWithCompletion != nil)
  144. case #selector(URLSessionTaskDelegate.urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)):
  145. return (taskWillPerformHTTPRedirection != nil || taskWillPerformHTTPRedirectionWithCompletion != nil)
  146. case #selector(URLSessionDataDelegate.urlSession(_:dataTask:didReceive:completionHandler:)):
  147. return (dataTaskDidReceiveResponse != nil || dataTaskDidReceiveResponseWithCompletion != nil)
  148. default:
  149. return type(of: self).instancesRespond(to: selector)
  150. }
  151. }
  152. }
  153. // MARK: - URLSessionDelegate
  154. extension SessionDelegate: URLSessionDelegate {
  155. /// Tells the delegate that the session has been invalidated.
  156. ///
  157. /// - parameter session: The session object that was invalidated.
  158. /// - parameter error: The error that caused invalidation, or nil if the invalidation was explicit.
  159. open func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) {
  160. sessionDidBecomeInvalidWithError?(session, error)
  161. }
  162. /// Requests credentials from the delegate in response to a session-level authentication request from the
  163. /// remote server.
  164. ///
  165. /// - parameter session: The session containing the task that requested authentication.
  166. /// - parameter challenge: An object that contains the request for authentication.
  167. /// - parameter completionHandler: A handler that your delegate method must call providing the disposition
  168. /// and credential.
  169. open func urlSession(
  170. _ session: URLSession,
  171. didReceive challenge: URLAuthenticationChallenge,
  172. completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void)
  173. {
  174. guard sessionDidReceiveChallengeWithCompletion == nil else {
  175. sessionDidReceiveChallengeWithCompletion?(session, challenge, completionHandler)
  176. return
  177. }
  178. var disposition: URLSession.AuthChallengeDisposition = .performDefaultHandling
  179. var credential: URLCredential?
  180. if let sessionDidReceiveChallenge = sessionDidReceiveChallenge {
  181. (disposition, credential) = sessionDidReceiveChallenge(session, challenge)
  182. } else if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
  183. let host = challenge.protectionSpace.host
  184. if
  185. let serverTrustPolicy = session.serverTrustPolicyManager?.serverTrustPolicy(forHost: host),
  186. let serverTrust = challenge.protectionSpace.serverTrust
  187. {
  188. if serverTrustPolicy.evaluate(serverTrust, forHost: host) {
  189. disposition = .useCredential
  190. credential = URLCredential(trust: serverTrust)
  191. } else {
  192. disposition = .cancelAuthenticationChallenge
  193. }
  194. }
  195. }
  196. completionHandler(disposition, credential)
  197. }
  198. #if !os(OSX)
  199. /// Tells the delegate that all messages enqueued for a session have been delivered.
  200. ///
  201. /// - parameter session: The session that no longer has any outstanding requests.
  202. open func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) {
  203. sessionDidFinishEventsForBackgroundURLSession?(session)
  204. }
  205. #endif
  206. }
  207. // MARK: - URLSessionTaskDelegate
  208. extension SessionDelegate: URLSessionTaskDelegate {
  209. /// Tells the delegate that the remote server requested an HTTP redirect.
  210. ///
  211. /// - parameter session: The session containing the task whose request resulted in a redirect.
  212. /// - parameter task: The task whose request resulted in a redirect.
  213. /// - parameter response: An object containing the server’s response to the original request.
  214. /// - parameter request: A URL request object filled out with the new location.
  215. /// - parameter completionHandler: A closure that your handler should call with either the value of the request
  216. /// parameter, a modified URL request object, or NULL to refuse the redirect and
  217. /// return the body of the redirect response.
  218. open func urlSession(
  219. _ session: URLSession,
  220. task: URLSessionTask,
  221. willPerformHTTPRedirection response: HTTPURLResponse,
  222. newRequest request: URLRequest,
  223. completionHandler: @escaping (URLRequest?) -> Void)
  224. {
  225. guard taskWillPerformHTTPRedirectionWithCompletion == nil else {
  226. taskWillPerformHTTPRedirectionWithCompletion?(session, task, response, request, completionHandler)
  227. return
  228. }
  229. var redirectRequest: URLRequest? = request
  230. if let taskWillPerformHTTPRedirection = taskWillPerformHTTPRedirection {
  231. redirectRequest = taskWillPerformHTTPRedirection(session, task, response, request)
  232. }
  233. completionHandler(redirectRequest)
  234. }
  235. /// Requests credentials from the delegate in response to an authentication request from the remote server.
  236. ///
  237. /// - parameter session: The session containing the task whose request requires authentication.
  238. /// - parameter task: The task whose request requires authentication.
  239. /// - parameter challenge: An object that contains the request for authentication.
  240. /// - parameter completionHandler: A handler that your delegate method must call providing the disposition
  241. /// and credential.
  242. open func urlSession(
  243. _ session: URLSession,
  244. task: URLSessionTask,
  245. didReceive challenge: URLAuthenticationChallenge,
  246. completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void)
  247. {
  248. guard taskDidReceiveChallengeWithCompletion == nil else {
  249. taskDidReceiveChallengeWithCompletion?(session, task, challenge, completionHandler)
  250. return
  251. }
  252. if let taskDidReceiveChallenge = taskDidReceiveChallenge {
  253. let result = taskDidReceiveChallenge(session, task, challenge)
  254. completionHandler(result.0, result.1)
  255. } else if let delegate = self[task]?.delegate {
  256. delegate.urlSession(
  257. session,
  258. task: task,
  259. didReceive: challenge,
  260. completionHandler: completionHandler
  261. )
  262. } else {
  263. urlSession(session, didReceive: challenge, completionHandler: completionHandler)
  264. }
  265. }
  266. /// Tells the delegate when a task requires a new request body stream to send to the remote server.
  267. ///
  268. /// - parameter session: The session containing the task that needs a new body stream.
  269. /// - parameter task: The task that needs a new body stream.
  270. /// - parameter completionHandler: A completion handler that your delegate method should call with the new body stream.
  271. open func urlSession(
  272. _ session: URLSession,
  273. task: URLSessionTask,
  274. needNewBodyStream completionHandler: @escaping (InputStream?) -> Void)
  275. {
  276. guard taskNeedNewBodyStreamWithCompletion == nil else {
  277. taskNeedNewBodyStreamWithCompletion?(session, task, completionHandler)
  278. return
  279. }
  280. if let taskNeedNewBodyStream = taskNeedNewBodyStream {
  281. completionHandler(taskNeedNewBodyStream(session, task))
  282. } else if let delegate = self[task]?.delegate {
  283. delegate.urlSession(session, task: task, needNewBodyStream: completionHandler)
  284. }
  285. }
  286. /// Periodically informs the delegate of the progress of sending body content to the server.
  287. ///
  288. /// - parameter session: The session containing the data task.
  289. /// - parameter task: The data task.
  290. /// - parameter bytesSent: The number of bytes sent since the last time this delegate method was called.
  291. /// - parameter totalBytesSent: The total number of bytes sent so far.
  292. /// - parameter totalBytesExpectedToSend: The expected length of the body data.
  293. open func urlSession(
  294. _ session: URLSession,
  295. task: URLSessionTask,
  296. didSendBodyData bytesSent: Int64,
  297. totalBytesSent: Int64,
  298. totalBytesExpectedToSend: Int64)
  299. {
  300. if let taskDidSendBodyData = taskDidSendBodyData {
  301. taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend)
  302. } else if let delegate = self[task]?.delegate as? UploadTaskDelegate {
  303. delegate.URLSession(
  304. session,
  305. task: task,
  306. didSendBodyData: bytesSent,
  307. totalBytesSent: totalBytesSent,
  308. totalBytesExpectedToSend: totalBytesExpectedToSend
  309. )
  310. }
  311. }
  312. #if !os(watchOS)
  313. /// Tells the delegate that the session finished collecting metrics for the task.
  314. ///
  315. /// - parameter session: The session collecting the metrics.
  316. /// - parameter task: The task whose metrics have been collected.
  317. /// - parameter metrics: The collected metrics.
  318. @available(iOS 10.0, macOS 10.12, tvOS 10.0, *)
  319. @objc(URLSession:task:didFinishCollectingMetrics:)
  320. open func urlSession(_ session: URLSession, task: URLSessionTask, didFinishCollecting metrics: URLSessionTaskMetrics) {
  321. self[task]?.delegate.metrics = metrics
  322. }
  323. #endif
  324. /// Tells the delegate that the task finished transferring data.
  325. ///
  326. /// - parameter session: The session containing the task whose request finished transferring data.
  327. /// - parameter task: The task whose request finished transferring data.
  328. /// - parameter error: If an error occurred, an error object indicating how the transfer failed, otherwise nil.
  329. open func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
  330. /// Executed after it is determined that the request is not going to be retried
  331. let completeTask: (URLSession, URLSessionTask, Error?) -> Void = { [weak self] session, task, error in
  332. guard let strongSelf = self else { return }
  333. if let taskDidComplete = strongSelf.taskDidComplete {
  334. taskDidComplete(session, task, error)
  335. } else if let delegate = strongSelf[task]?.delegate {
  336. delegate.urlSession(session, task: task, didCompleteWithError: error)
  337. }
  338. NotificationCenter.default.post(
  339. name: Notification.Name.Task.DidComplete,
  340. object: strongSelf,
  341. userInfo: [Notification.Key.Task: task]
  342. )
  343. strongSelf[task] = nil
  344. }
  345. guard let request = self[task], let sessionManager = sessionManager else {
  346. completeTask(session, task, error)
  347. return
  348. }
  349. // Run all validations on the request before checking if an error occurred
  350. request.validations.forEach { $0() }
  351. // Determine whether an error has occurred
  352. var error: Error? = error
  353. if let taskDelegate = self[task]?.delegate, taskDelegate.error != nil {
  354. error = taskDelegate.error
  355. }
  356. /// If an error occurred and the retrier is set, asynchronously ask the retrier if the request
  357. /// should be retried. Otherwise, complete the task by notifying the task delegate.
  358. if let retrier = retrier, let error = error {
  359. retrier.should(sessionManager, retry: request, with: error) { [weak self] shouldRetry, delay in
  360. guard shouldRetry else { completeTask(session, task, error) ; return }
  361. DispatchQueue.utility.after(delay) { [weak self] in
  362. guard let strongSelf = self else { return }
  363. let retrySucceeded = strongSelf.sessionManager?.retry(request) ?? false
  364. if retrySucceeded, let task = request.task {
  365. strongSelf[task] = request
  366. return
  367. } else {
  368. completeTask(session, task, error)
  369. }
  370. }
  371. }
  372. } else {
  373. completeTask(session, task, error)
  374. }
  375. }
  376. }
  377. // MARK: - URLSessionDataDelegate
  378. extension SessionDelegate: URLSessionDataDelegate {
  379. /// Tells the delegate that the data task received the initial reply (headers) from the server.
  380. ///
  381. /// - parameter session: The session containing the data task that received an initial reply.
  382. /// - parameter dataTask: The data task that received an initial reply.
  383. /// - parameter response: A URL response object populated with headers.
  384. /// - parameter completionHandler: A completion handler that your code calls to continue the transfer, passing a
  385. /// constant to indicate whether the transfer should continue as a data task or
  386. /// should become a download task.
  387. open func urlSession(
  388. _ session: URLSession,
  389. dataTask: URLSessionDataTask,
  390. didReceive response: URLResponse,
  391. completionHandler: @escaping (URLSession.ResponseDisposition) -> Void)
  392. {
  393. guard dataTaskDidReceiveResponseWithCompletion == nil else {
  394. dataTaskDidReceiveResponseWithCompletion?(session, dataTask, response, completionHandler)
  395. return
  396. }
  397. var disposition: URLSession.ResponseDisposition = .allow
  398. if let dataTaskDidReceiveResponse = dataTaskDidReceiveResponse {
  399. disposition = dataTaskDidReceiveResponse(session, dataTask, response)
  400. }
  401. completionHandler(disposition)
  402. }
  403. /// Tells the delegate that the data task was changed to a download task.
  404. ///
  405. /// - parameter session: The session containing the task that was replaced by a download task.
  406. /// - parameter dataTask: The data task that was replaced by a download task.
  407. /// - parameter downloadTask: The new download task that replaced the data task.
  408. open func urlSession(
  409. _ session: URLSession,
  410. dataTask: URLSessionDataTask,
  411. didBecome downloadTask: URLSessionDownloadTask)
  412. {
  413. if let dataTaskDidBecomeDownloadTask = dataTaskDidBecomeDownloadTask {
  414. dataTaskDidBecomeDownloadTask(session, dataTask, downloadTask)
  415. } else {
  416. self[downloadTask]?.delegate = DownloadTaskDelegate(task: downloadTask)
  417. }
  418. }
  419. /// Tells the delegate that the data task has received some of the expected data.
  420. ///
  421. /// - parameter session: The session containing the data task that provided data.
  422. /// - parameter dataTask: The data task that provided data.
  423. /// - parameter data: A data object containing the transferred data.
  424. open func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
  425. if let dataTaskDidReceiveData = dataTaskDidReceiveData {
  426. dataTaskDidReceiveData(session, dataTask, data)
  427. } else if let delegate = self[dataTask]?.delegate as? DataTaskDelegate {
  428. delegate.urlSession(session, dataTask: dataTask, didReceive: data)
  429. }
  430. }
  431. /// Asks the delegate whether the data (or upload) task should store the response in the cache.
  432. ///
  433. /// - parameter session: The session containing the data (or upload) task.
  434. /// - parameter dataTask: The data (or upload) task.
  435. /// - parameter proposedResponse: The default caching behavior. This behavior is determined based on the current
  436. /// caching policy and the values of certain received headers, such as the Pragma
  437. /// and Cache-Control headers.
  438. /// - parameter completionHandler: A block that your handler must call, providing either the original proposed
  439. /// response, a modified version of that response, or NULL to prevent caching the
  440. /// response. If your delegate implements this method, it must call this completion
  441. /// handler; otherwise, your app leaks memory.
  442. open func urlSession(
  443. _ session: URLSession,
  444. dataTask: URLSessionDataTask,
  445. willCacheResponse proposedResponse: CachedURLResponse,
  446. completionHandler: @escaping (CachedURLResponse?) -> Void)
  447. {
  448. guard dataTaskWillCacheResponseWithCompletion == nil else {
  449. dataTaskWillCacheResponseWithCompletion?(session, dataTask, proposedResponse, completionHandler)
  450. return
  451. }
  452. if let dataTaskWillCacheResponse = dataTaskWillCacheResponse {
  453. completionHandler(dataTaskWillCacheResponse(session, dataTask, proposedResponse))
  454. } else if let delegate = self[dataTask]?.delegate as? DataTaskDelegate {
  455. delegate.urlSession(
  456. session,
  457. dataTask: dataTask,
  458. willCacheResponse: proposedResponse,
  459. completionHandler: completionHandler
  460. )
  461. } else {
  462. completionHandler(proposedResponse)
  463. }
  464. }
  465. }
  466. // MARK: - URLSessionDownloadDelegate
  467. extension SessionDelegate: URLSessionDownloadDelegate {
  468. /// Tells the delegate that a download task has finished downloading.
  469. ///
  470. /// - parameter session: The session containing the download task that finished.
  471. /// - parameter downloadTask: The download task that finished.
  472. /// - parameter location: A file URL for the temporary file. Because the file is temporary, you must either
  473. /// open the file for reading or move it to a permanent location in your app’s sandbox
  474. /// container directory before returning from this delegate method.
  475. open func urlSession(
  476. _ session: URLSession,
  477. downloadTask: URLSessionDownloadTask,
  478. didFinishDownloadingTo location: URL)
  479. {
  480. if let downloadTaskDidFinishDownloadingToURL = downloadTaskDidFinishDownloadingToURL {
  481. downloadTaskDidFinishDownloadingToURL(session, downloadTask, location)
  482. } else if let delegate = self[downloadTask]?.delegate as? DownloadTaskDelegate {
  483. delegate.urlSession(session, downloadTask: downloadTask, didFinishDownloadingTo: location)
  484. }
  485. }
  486. /// Periodically informs the delegate about the download’s progress.
  487. ///
  488. /// - parameter session: The session containing the download task.
  489. /// - parameter downloadTask: The download task.
  490. /// - parameter bytesWritten: The number of bytes transferred since the last time this delegate
  491. /// method was called.
  492. /// - parameter totalBytesWritten: The total number of bytes transferred so far.
  493. /// - parameter totalBytesExpectedToWrite: The expected length of the file, as provided by the Content-Length
  494. /// header. If this header was not provided, the value is
  495. /// `NSURLSessionTransferSizeUnknown`.
  496. open func urlSession(
  497. _ session: URLSession,
  498. downloadTask: URLSessionDownloadTask,
  499. didWriteData bytesWritten: Int64,
  500. totalBytesWritten: Int64,
  501. totalBytesExpectedToWrite: Int64)
  502. {
  503. if let downloadTaskDidWriteData = downloadTaskDidWriteData {
  504. downloadTaskDidWriteData(session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite)
  505. } else if let delegate = self[downloadTask]?.delegate as? DownloadTaskDelegate {
  506. delegate.urlSession(
  507. session,
  508. downloadTask: downloadTask,
  509. didWriteData: bytesWritten,
  510. totalBytesWritten: totalBytesWritten,
  511. totalBytesExpectedToWrite: totalBytesExpectedToWrite
  512. )
  513. }
  514. }
  515. /// Tells the delegate that the download task has resumed downloading.
  516. ///
  517. /// - parameter session: The session containing the download task that finished.
  518. /// - parameter downloadTask: The download task that resumed. See explanation in the discussion.
  519. /// - parameter fileOffset: If the file's cache policy or last modified date prevents reuse of the
  520. /// existing content, then this value is zero. Otherwise, this value is an
  521. /// integer representing the number of bytes on disk that do not need to be
  522. /// retrieved again.
  523. /// - parameter expectedTotalBytes: The expected length of the file, as provided by the Content-Length header.
  524. /// If this header was not provided, the value is NSURLSessionTransferSizeUnknown.
  525. open func urlSession(
  526. _ session: URLSession,
  527. downloadTask: URLSessionDownloadTask,
  528. didResumeAtOffset fileOffset: Int64,
  529. expectedTotalBytes: Int64)
  530. {
  531. if let downloadTaskDidResumeAtOffset = downloadTaskDidResumeAtOffset {
  532. downloadTaskDidResumeAtOffset(session, downloadTask, fileOffset, expectedTotalBytes)
  533. } else if let delegate = self[downloadTask]?.delegate as? DownloadTaskDelegate {
  534. delegate.urlSession(
  535. session,
  536. downloadTask: downloadTask,
  537. didResumeAtOffset: fileOffset,
  538. expectedTotalBytes: expectedTotalBytes
  539. )
  540. }
  541. }
  542. }
  543. // MARK: - URLSessionStreamDelegate
  544. #if !os(watchOS)
  545. extension SessionDelegate: URLSessionStreamDelegate {
  546. /// Tells the delegate that the read side of the connection has been closed.
  547. ///
  548. /// - parameter session: The session.
  549. /// - parameter streamTask: The stream task.
  550. open func urlSession(_ session: URLSession, readClosedFor streamTask: URLSessionStreamTask) {
  551. streamTaskReadClosed?(session, streamTask)
  552. }
  553. /// Tells the delegate that the write side of the connection has been closed.
  554. ///
  555. /// - parameter session: The session.
  556. /// - parameter streamTask: The stream task.
  557. open func urlSession(_ session: URLSession, writeClosedFor streamTask: URLSessionStreamTask) {
  558. streamTaskWriteClosed?(session, streamTask)
  559. }
  560. /// Tells the delegate that the system has determined that a better route to the host is available.
  561. ///
  562. /// - parameter session: The session.
  563. /// - parameter streamTask: The stream task.
  564. open func urlSession(_ session: URLSession, betterRouteDiscoveredFor streamTask: URLSessionStreamTask) {
  565. streamTaskBetterRouteDiscovered?(session, streamTask)
  566. }
  567. /// Tells the delegate that the stream task has been completed and provides the unopened stream objects.
  568. ///
  569. /// - parameter session: The session.
  570. /// - parameter streamTask: The stream task.
  571. /// - parameter inputStream: The new input stream.
  572. /// - parameter outputStream: The new output stream.
  573. open func urlSession(
  574. _ session: URLSession,
  575. streamTask: URLSessionStreamTask,
  576. didBecome inputStream: InputStream,
  577. outputStream: OutputStream)
  578. {
  579. streamTaskDidBecomeInputAndOutputStreams?(session, streamTask, inputStream, outputStream)
  580. }
  581. }
  582. #endif