SessionDelegate.swift 32 KB

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