ImageDownloader.swift 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  1. //
  2. // ImageDownloader.swift
  3. // Kingfisher
  4. //
  5. // Created by Wei Wang on 15/4/6.
  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. #if os(macOS)
  27. import AppKit
  28. #else
  29. import UIKit
  30. #endif
  31. /// Represents a success result of an image downloading progress.
  32. public struct ImageLoadingResult {
  33. /// The downloaded image.
  34. public let image: Image
  35. /// Original URL of the image request.
  36. public let url: URL?
  37. /// The raw data received from downloader.
  38. public let originalData: Data
  39. }
  40. /// Represents a task of an image downloading process.
  41. public struct DownloadTask {
  42. /// The `SessionDataTask` object bounded to this download task. Multiple `DownloadTask`s could refer
  43. /// to a same `sessionTask`. This is an optimization in Kingfisher to prevent multiple downloading task
  44. /// for the same URL resource at the same time.
  45. ///
  46. /// When you `cancel` a `DownloadTask`, this `SessionDataTask` and its cancel token will be pass through.
  47. /// You can use them to identify the cancelled task.
  48. public let sessionTask: SessionDataTask
  49. /// The cancel token which is used to cancel the task. This is only for identify the task when it is cancelled.
  50. /// To cancel a `DownloadTask`, use `cancel` instead.
  51. public let cancelToken: SessionDataTask.CancelToken
  52. /// Cancel this task if it is running. It will do nothing if this task is not running.
  53. ///
  54. /// - Note:
  55. /// In Kingfisher, there is an optimization to prevent starting another download task if the target URL is being
  56. /// downloading. However, even when internally no new session task created, a `DownloadTask` will be still created
  57. /// and returned when you call related methods, but it will share the session downloading task with a previous task.
  58. /// In this case, if multiple `DownloadTask`s share a single session download task, cancelling a `DownloadTask`
  59. /// does not affect other `DownloadTask`s.
  60. ///
  61. /// If you need to cancel all `DownloadTask`s of a url, use `ImageDownloader.cancel(url:)`. If you need to cancel
  62. /// all downloading tasks of an `ImageDownloader`, use `ImageDownloader.cancelAll()`.
  63. public func cancel() {
  64. sessionTask.cancel(token: cancelToken)
  65. }
  66. }
  67. extension DownloadTask {
  68. enum WrappedTask {
  69. case download(DownloadTask)
  70. case dataProviding
  71. func cancel() {
  72. switch self {
  73. case .download(let task): task.cancel()
  74. case .dataProviding: break
  75. }
  76. }
  77. var value: DownloadTask? {
  78. switch self {
  79. case .download(let task): return task
  80. case .dataProviding: return nil
  81. }
  82. }
  83. }
  84. }
  85. /// Represents a downloading manager for requesting the image with a URL from server.
  86. open class ImageDownloader {
  87. // MARK: Singleton
  88. /// The default downloader.
  89. public static let `default` = ImageDownloader(name: "default")
  90. // MARK: Public Properties
  91. /// The duration before the downloading is timeout. Default is 15 seconds.
  92. open var downloadTimeout: TimeInterval = 15.0
  93. /// A set of trusted hosts when receiving server trust challenges. A challenge with host name contained in this
  94. /// set will be ignored. You can use this set to specify the self-signed site. It only will be used if you don't
  95. /// specify the `authenticationChallengeResponder`.
  96. ///
  97. /// If `authenticationChallengeResponder` is set, this property will be ignored and the implementation of
  98. /// `authenticationChallengeResponder` will be used instead.
  99. open var trustedHosts: Set<String>?
  100. /// Use this to set supply a configuration for the downloader. By default,
  101. /// NSURLSessionConfiguration.ephemeralSessionConfiguration() will be used.
  102. ///
  103. /// You could change the configuration before a downloading task starts.
  104. /// A configuration without persistent storage for caches is requested for downloader working correctly.
  105. open var sessionConfiguration = URLSessionConfiguration.ephemeral {
  106. didSet {
  107. session.invalidateAndCancel()
  108. session = URLSession(configuration: sessionConfiguration, delegate: sessionDelegate, delegateQueue: nil)
  109. }
  110. }
  111. /// Whether the download requests should use pipeline or not. Default is false.
  112. open var requestsUsePipelining = false
  113. /// Delegate of this `ImageDownloader` object. See `ImageDownloaderDelegate` protocol for more.
  114. open weak var delegate: ImageDownloaderDelegate?
  115. /// A responder for authentication challenge.
  116. /// Downloader will forward the received authentication challenge for the downloading session to this responder.
  117. open weak var authenticationChallengeResponder: AuthenticationChallengeResponsable?
  118. private let name: String
  119. private let sessionDelegate: SessionDelegate
  120. private var session: URLSession
  121. // MARK: Initializers
  122. /// Creates a downloader with name.
  123. ///
  124. /// - Parameter name: The name for the downloader. It should not be empty.
  125. public init(name: String) {
  126. if name.isEmpty {
  127. fatalError("[Kingfisher] You should specify a name for the downloader. "
  128. + "A downloader with empty name is not permitted.")
  129. }
  130. self.name = name
  131. sessionDelegate = SessionDelegate()
  132. session = URLSession(
  133. configuration: sessionConfiguration,
  134. delegate: sessionDelegate,
  135. delegateQueue: nil)
  136. authenticationChallengeResponder = self
  137. setupSessionHandler()
  138. }
  139. deinit { session.invalidateAndCancel() }
  140. private func setupSessionHandler() {
  141. sessionDelegate.onReceiveSessionChallenge.delegate(on: self) { (self, invoke) in
  142. self.authenticationChallengeResponder?.downloader(self, didReceive: invoke.1, completionHandler: invoke.2)
  143. }
  144. sessionDelegate.onReceiveSessionTaskChallenge.delegate(on: self) { (self, invoke) in
  145. self.authenticationChallengeResponder?.downloader(
  146. self, task: invoke.1, didReceive: invoke.2, completionHandler: invoke.3)
  147. }
  148. sessionDelegate.onValidStatusCode.delegate(on: self) { (self, code) in
  149. return (self.delegate ?? self).isValidStatusCode(code, for: self)
  150. }
  151. sessionDelegate.onDownloadingFinished.delegate(on: self) { (self, value) in
  152. let (url, result) = value
  153. do {
  154. let value = try result.get()
  155. self.delegate?.imageDownloader(self, didFinishDownloadingImageForURL: url, with: value, error: nil)
  156. } catch {
  157. self.delegate?.imageDownloader(self, didFinishDownloadingImageForURL: url, with: nil, error: error)
  158. }
  159. }
  160. sessionDelegate.onDidDownloadData.delegate(on: self) { (self, task) in
  161. guard let url = task.task.originalRequest?.url else {
  162. return task.mutableData
  163. }
  164. return (self.delegate ?? self).imageDownloader(self, didDownload: task.mutableData, for: url)
  165. }
  166. }
  167. @discardableResult
  168. func downloadImage(
  169. with url: URL,
  170. options: KingfisherParsedOptionsInfo,
  171. progressBlock: DownloadProgressBlock? = nil,
  172. completionHandler: ((Result<ImageLoadingResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
  173. {
  174. // Creates default request.
  175. var request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: downloadTimeout)
  176. request.httpShouldUsePipelining = requestsUsePipelining
  177. if let requestModifier = options.requestModifier {
  178. // Modifies request before sending.
  179. guard let r = requestModifier.modified(for: request) else {
  180. options.callbackQueue.execute {
  181. completionHandler?(.failure(KingfisherError.requestError(reason: .emptyRequest)))
  182. }
  183. return nil
  184. }
  185. request = r
  186. }
  187. // There is a possibility that request modifier changed the url to `nil` or empty.
  188. // In this case, throw an error.
  189. guard let url = request.url, !url.absoluteString.isEmpty else {
  190. options.callbackQueue.execute {
  191. completionHandler?(.failure(KingfisherError.requestError(reason: .invalidURL(request: request))))
  192. }
  193. return nil
  194. }
  195. // Wraps `progressBlock` and `completionHandler` to `onProgress` and `onCompleted` respectively.
  196. let onProgress = progressBlock.map {
  197. block -> Delegate<(Int64, Int64), Void> in
  198. let delegate = Delegate<(Int64, Int64), Void>()
  199. delegate.delegate(on: self) { (_, progress) in
  200. let (downloaded, total) = progress
  201. block(downloaded, total)
  202. }
  203. return delegate
  204. }
  205. let onCompleted = completionHandler.map {
  206. block -> Delegate<Result<ImageLoadingResult, KingfisherError>, Void> in
  207. let delegate = Delegate<Result<ImageLoadingResult, KingfisherError>, Void>()
  208. delegate.delegate(on: self) { (_, result) in
  209. block(result)
  210. }
  211. return delegate
  212. }
  213. // SessionDataTask.TaskCallback is a wrapper for `onProgress`, `onCompleted` and `options` (for processor info)
  214. let callback = SessionDataTask.TaskCallback(
  215. onProgress: onProgress, onCompleted: onCompleted, options: options)
  216. // Ready to start download. Add it to session task manager (`sessionHandler`)
  217. let downloadTask: DownloadTask
  218. if let existingTask = sessionDelegate.task(for: url) {
  219. downloadTask = sessionDelegate.append(existingTask, url: url, callback: callback)
  220. } else {
  221. let sessionDataTask = session.dataTask(with: request)
  222. sessionDataTask.priority = options.downloadPriority
  223. downloadTask = sessionDelegate.add(sessionDataTask, url: url, callback: callback)
  224. }
  225. let sessionTask = downloadTask.sessionTask
  226. // Start the session task if not started yet.
  227. if !sessionTask.started {
  228. sessionTask.onTaskDone.delegate(on: self) { (self, done) in
  229. // Underlying downloading finishes.
  230. // result: Result<(Data, URLResponse?)>, callbacks: [TaskCallback]
  231. let (result, callbacks) = done
  232. // Before processing the downloaded data.
  233. do {
  234. let value = try result.get()
  235. self.delegate?.imageDownloader(
  236. self,
  237. didFinishDownloadingImageForURL: url,
  238. with: value.1,
  239. error: nil)
  240. } catch {
  241. self.delegate?.imageDownloader(
  242. self,
  243. didFinishDownloadingImageForURL: url,
  244. with: nil,
  245. error: error)
  246. }
  247. switch result {
  248. // Download finished. Now process the data to an image.
  249. case .success(let (data, response)):
  250. let processor = ImageDataProcessor(
  251. data: data, callbacks: callbacks, processingQueue: options.processingQueue)
  252. processor.onImageProcessed.delegate(on: self) { (self, result) in
  253. // `onImageProcessed` will be called for `callbacks.count` times, with each
  254. // `SessionDataTask.TaskCallback` as the input parameter.
  255. // result: Result<Image>, callback: SessionDataTask.TaskCallback
  256. let (result, callback) = result
  257. if let image = try? result.get() {
  258. self.delegate?.imageDownloader(self, didDownload: image, for: url, with: response)
  259. }
  260. let imageResult = result.map { ImageLoadingResult(image: $0, url: url, originalData: data) }
  261. let queue = callback.options.callbackQueue
  262. queue.execute { callback.onCompleted?.call(imageResult) }
  263. }
  264. processor.process()
  265. case .failure(let error):
  266. callbacks.forEach { callback in
  267. let queue = callback.options.callbackQueue
  268. queue.execute { callback.onCompleted?.call(.failure(error)) }
  269. }
  270. }
  271. }
  272. delegate?.imageDownloader(self, willDownloadImageForURL: url, with: request)
  273. sessionTask.resume()
  274. }
  275. return downloadTask
  276. }
  277. // MARK: Dowloading Task
  278. /// Downloads an image with a URL and option.
  279. ///
  280. /// - Parameters:
  281. /// - url: Target URL.
  282. /// - options: The options could control download behavior. See `KingfisherOptionsInfo`.
  283. /// - progressBlock: Called when the download progress updated. This block will be always be called in main queue.
  284. /// - completionHandler: Called when the download progress finishes. This block will be called in the queue
  285. /// defined in `.callbackQueue` in `options` parameter.
  286. /// - Returns: A downloading task. You could call `cancel` on it to stop the download task.
  287. @discardableResult
  288. open func downloadImage(
  289. with url: URL,
  290. options: KingfisherOptionsInfo? = nil,
  291. progressBlock: DownloadProgressBlock? = nil,
  292. completionHandler: ((Result<ImageLoadingResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
  293. {
  294. return downloadImage(
  295. with: url,
  296. options: KingfisherParsedOptionsInfo(options),
  297. progressBlock: progressBlock,
  298. completionHandler: completionHandler)
  299. }
  300. }
  301. // MARK: Cancelling Task
  302. extension ImageDownloader {
  303. /// Cancel all downloading tasks for this `ImageDownloader`. It will trigger the completion handlers
  304. /// for all not-yet-finished downloading tasks.
  305. ///
  306. /// If you need to only cancel a certain task, call `cancel()` on the `DownloadTask`
  307. /// returned by the downloading methods. If you need to cancel all `DownloadTask`s of a certain url,
  308. /// use `ImageDownloader.cancel(url:)`.
  309. public func cancelAll() {
  310. sessionDelegate.cancelAll()
  311. }
  312. /// Cancel all downloading tasks for a given URL. It will trigger the completion handlers for
  313. /// all not-yet-finished downloading tasks for the URL.
  314. ///
  315. /// - Parameter url: The URL which you want to cancel downloading.
  316. public func cancel(url: URL) {
  317. sessionDelegate.cancel(url: url)
  318. }
  319. }
  320. // Use the default implementation from extension of `AuthenticationChallengeResponsable`.
  321. extension ImageDownloader: AuthenticationChallengeResponsable {}
  322. // Use the default implementation from extension of `ImageDownloaderDelegate`.
  323. extension ImageDownloader: ImageDownloaderDelegate {}