SessionDelegate.swift 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  1. //
  2. // SessionDelegate.swift
  3. // Kingfisher
  4. //
  5. // Created by Wei Wang on 2018/11/1.
  6. //
  7. // Copyright (c) 2019 Wei Wang <onevcat@gmail.com>
  8. //
  9. // Permission is hereby granted, free of charge, to any person obtaining a copy
  10. // of this software and associated documentation files (the "Software"), to deal
  11. // in the Software without restriction, including without limitation the rights
  12. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  13. // copies of the Software, and to permit persons to whom the Software is
  14. // furnished to do so, subject to the following conditions:
  15. //
  16. // The above copyright notice and this permission notice shall be included in
  17. // all copies or substantial portions of the Software.
  18. //
  19. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  20. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  21. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  22. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  23. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  24. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  25. // THE SOFTWARE.
  26. import Foundation
  27. // Represents the delegate object of downloader session. It also behave like a task manager for downloading.
  28. @objc(KFSessionDelegate) // Fix for ObjC header name conflicting. https://github.com/onevcat/Kingfisher/issues/1530
  29. class SessionDelegate: NSObject {
  30. typealias SessionChallengeFunc = (
  31. URLSession,
  32. URLAuthenticationChallenge,
  33. (URLSession.AuthChallengeDisposition, URLCredential?) -> Void
  34. )
  35. typealias SessionTaskChallengeFunc = (
  36. URLSession,
  37. URLSessionTask,
  38. URLAuthenticationChallenge,
  39. (URLSession.AuthChallengeDisposition, URLCredential?) -> Void
  40. )
  41. private var tasks: [URL: SessionDataTask] = [:]
  42. private let lock = NSLock()
  43. private weak var extraHandler: URLSessionDataDelegate?
  44. let onValidStatusCode = Delegate<Int, Bool>()
  45. let onDownloadingFinished = Delegate<(URL, Result<URLResponse, KingfisherError>), Void>()
  46. let onDidDownloadData = Delegate<SessionDataTask, Data?>()
  47. let onReceiveSessionChallenge = Delegate<SessionChallengeFunc, Void>()
  48. let onReceiveSessionTaskChallenge = Delegate<SessionTaskChallengeFunc, Void>()
  49. func add(
  50. _ dataTask: URLSessionDataTask,
  51. url: URL,
  52. callback: SessionDataTask.TaskCallback) -> DownloadTask
  53. {
  54. lock.lock()
  55. defer { lock.unlock() }
  56. // Create a new task if necessary.
  57. let task = SessionDataTask(task: dataTask)
  58. task.onCallbackCancelled.delegate(on: self) { [weak task] (self, value) in
  59. guard let task = task else { return }
  60. let (token, callback) = value
  61. let error = KingfisherError.requestError(reason: .taskCancelled(task: task, token: token))
  62. task.onTaskDone.call((.failure(error), [callback]))
  63. // No other callbacks waiting, we can clear the task now.
  64. if !task.containsCallbacks {
  65. let dataTask = task.task
  66. self.cancelTask(dataTask)
  67. self.remove(task)
  68. }
  69. }
  70. let token = task.addCallback(callback)
  71. tasks[url] = task
  72. return DownloadTask(sessionTask: task, cancelToken: token)
  73. }
  74. private func cancelTask(_ dataTask: URLSessionDataTask) {
  75. lock.lock()
  76. defer { lock.unlock() }
  77. dataTask.cancel()
  78. }
  79. func append(
  80. _ task: SessionDataTask,
  81. url: URL,
  82. callback: SessionDataTask.TaskCallback) -> DownloadTask
  83. {
  84. let token = task.addCallback(callback)
  85. return DownloadTask(sessionTask: task, cancelToken: token)
  86. }
  87. private func remove(_ task: SessionDataTask) {
  88. lock.lock()
  89. defer { lock.unlock() }
  90. guard let url = task.originalURL else {
  91. return
  92. }
  93. tasks[url] = nil
  94. }
  95. private func task(for task: URLSessionTask) -> SessionDataTask? {
  96. lock.lock()
  97. defer { lock.unlock() }
  98. guard let url = task.originalRequest?.url else {
  99. return nil
  100. }
  101. guard let sessionTask = tasks[url] else {
  102. return nil
  103. }
  104. guard sessionTask.task.taskIdentifier == task.taskIdentifier else {
  105. return nil
  106. }
  107. return sessionTask
  108. }
  109. func task(for url: URL) -> SessionDataTask? {
  110. lock.lock()
  111. defer { lock.unlock() }
  112. return tasks[url]
  113. }
  114. func cancelAll() {
  115. lock.lock()
  116. let taskValues = tasks.values
  117. lock.unlock()
  118. for task in taskValues {
  119. task.forceCancel()
  120. }
  121. }
  122. func cancel(url: URL) {
  123. lock.lock()
  124. let task = tasks[url]
  125. lock.unlock()
  126. task?.forceCancel()
  127. }
  128. /// You could set the extra handler before a downloading task starts.
  129. func setExtraHandler(_ handler: URLSessionDataDelegate?) {
  130. extraHandler = handler
  131. }
  132. func getExtraHandler() -> URLSessionDataDelegate? {
  133. return extraHandler
  134. }
  135. }
  136. extension SessionDelegate: URLSessionDataDelegate {
  137. func urlSession(
  138. _ session: URLSession,
  139. dataTask: URLSessionDataTask,
  140. didReceive response: URLResponse,
  141. completionHandler: @escaping (URLSession.ResponseDisposition) -> Void)
  142. {
  143. guard let httpResponse = response as? HTTPURLResponse else {
  144. let error = KingfisherError.responseError(reason: .invalidURLResponse(response: response))
  145. onCompleted(task: dataTask, result: .failure(error))
  146. completionHandler(.cancel)
  147. return
  148. }
  149. let httpStatusCode = httpResponse.statusCode
  150. guard onValidStatusCode.call(httpStatusCode) == true else {
  151. let error = KingfisherError.responseError(reason: .invalidHTTPStatusCode(response: httpResponse))
  152. onCompleted(task: dataTask, result: .failure(error))
  153. completionHandler(.cancel)
  154. return
  155. }
  156. completionHandler(.allow)
  157. }
  158. func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
  159. guard let task = self.task(for: dataTask) else {
  160. return
  161. }
  162. task.didReceiveData(data)
  163. task.callbacks.forEach { callback in
  164. callback.options.onDataReceived?.forEach { sideEffect in
  165. sideEffect.onDataReceived(session, task: task, data: data)
  166. }
  167. }
  168. }
  169. func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
  170. guard let sessionTask = self.task(for: task) else { return }
  171. if let url = sessionTask.originalURL {
  172. let result: Result<URLResponse, KingfisherError>
  173. if let error = error {
  174. result = .failure(KingfisherError.responseError(reason: .URLSessionError(error: error)))
  175. } else if let response = task.response {
  176. result = .success(response)
  177. } else {
  178. result = .failure(KingfisherError.responseError(reason: .noURLResponse(task: sessionTask)))
  179. }
  180. onDownloadingFinished.call((url, result))
  181. }
  182. let result: Result<(Data, URLResponse?), KingfisherError>
  183. if let error = error {
  184. result = .failure(KingfisherError.responseError(reason: .URLSessionError(error: error)))
  185. } else {
  186. if let data = onDidDownloadData.call(sessionTask) {
  187. result = .success((data, task.response))
  188. } else {
  189. result = .failure(KingfisherError.responseError(reason: .dataModifyingFailed(task: sessionTask)))
  190. }
  191. }
  192. onCompleted(task: task, result: result)
  193. }
  194. func urlSession(
  195. _ session: URLSession,
  196. didReceive challenge: URLAuthenticationChallenge,
  197. completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void)
  198. {
  199. onReceiveSessionChallenge.call((session, challenge, completionHandler))
  200. }
  201. func urlSession(
  202. _ session: URLSession,
  203. task: URLSessionTask,
  204. didReceive challenge: URLAuthenticationChallenge,
  205. completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void)
  206. {
  207. onReceiveSessionTaskChallenge.call((session, task, challenge, completionHandler))
  208. }
  209. func urlSession(
  210. _ session: URLSession,
  211. task: URLSessionTask,
  212. willPerformHTTPRedirection response: HTTPURLResponse,
  213. newRequest request: URLRequest,
  214. completionHandler: @escaping (URLRequest?) -> Void)
  215. {
  216. guard let sessionDataTask = self.task(for: task),
  217. let redirectHandler = Array(sessionDataTask.callbacks).last?.options.redirectHandler else
  218. {
  219. completionHandler(request)
  220. return
  221. }
  222. redirectHandler.handleHTTPRedirection(
  223. for: sessionDataTask,
  224. response: response,
  225. newRequest: request,
  226. completionHandler: completionHandler)
  227. }
  228. private func onCompleted(task: URLSessionTask, result: Result<(Data, URLResponse?), KingfisherError>) {
  229. guard let sessionTask = self.task(for: task) else {
  230. return
  231. }
  232. remove(sessionTask)
  233. sessionTask.onTaskDone.call((result, sessionTask.callbacks))
  234. }
  235. // MARK: - extraHandler
  236. @available(iOS 7.0, OSX 11.0, tvOS 9.0, watchOS 2.0, *)
  237. func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) {
  238. extraHandler?.urlSessionDidFinishEvents?(forBackgroundURLSession: session)
  239. }
  240. func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) {
  241. extraHandler?.urlSession?(session, didBecomeInvalidWithError: error)
  242. }
  243. @available(iOS 11.0, OSX 10.13, tvOS 11.0, watchOS 4.0, *)
  244. func urlSession(_ session: URLSession, taskIsWaitingForConnectivity task: URLSessionTask) {
  245. extraHandler?.urlSession?(session, taskIsWaitingForConnectivity: task)
  246. }
  247. @available(iOS 10.0, OSX 10.12, tvOS 10.0, watchOS 3.0, *)
  248. func urlSession(_ session: URLSession, task: URLSessionTask, didFinishCollecting metrics: URLSessionTaskMetrics) {
  249. extraHandler?.urlSession?(session, task: task, didFinishCollecting: metrics)
  250. }
  251. @available(iOS 9.0, OSX 10.11, tvOS 9.0, watchOS 2.0, *)
  252. func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didBecome streamTask: URLSessionStreamTask) {
  253. extraHandler?.urlSession?(session, dataTask: dataTask, didBecome: streamTask)
  254. }
  255. func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didBecome downloadTask: URLSessionDownloadTask) {
  256. extraHandler?.urlSession?(session, dataTask: dataTask, didBecome: downloadTask)
  257. }
  258. func urlSession(_ session: URLSession, task: URLSessionTask, needNewBodyStream completionHandler: @escaping (InputStream?) -> Void) {
  259. extraHandler?.urlSession?(session, task: task, needNewBodyStream: completionHandler)
  260. }
  261. func urlSession(_ session: URLSession, task: URLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
  262. extraHandler?.urlSession?(session, task: task, didSendBodyData: bytesSent, totalBytesSent: totalBytesSent, totalBytesExpectedToSend: totalBytesExpectedToSend)
  263. }
  264. func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, willCacheResponse proposedResponse: CachedURLResponse, completionHandler: @escaping (CachedURLResponse?) -> Void) {
  265. extraHandler?.urlSession?(session, dataTask: dataTask, willCacheResponse: proposedResponse, completionHandler: completionHandler)
  266. }
  267. @available(iOS 11.0, OSX 10.13, tvOS 11.0, watchOS 4.0, *)
  268. func urlSession(_ session: URLSession, task: URLSessionTask, willBeginDelayedRequest request: URLRequest, completionHandler: @escaping (URLSession.DelayedRequestDisposition, URLRequest?) -> Void) {
  269. extraHandler?.urlSession?(session, task: task, willBeginDelayedRequest: request, completionHandler: completionHandler)
  270. }
  271. }