ImagePrefetcher.swift 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. //
  2. // ImagePrefetcher.swift
  3. // Kingfisher
  4. //
  5. // Created by Claire Knight <claire.knight@moggytech.co.uk> on 24/02/2016
  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. /// Progress update block of prefetcher when initialized with a list of resources.
  32. ///
  33. /// - `skippedResources`: An array of resources that are already cached before the prefetching starting.
  34. /// - `failedResources`: An array of resources that fail to be downloaded. It could because of being cancelled while
  35. /// downloading, encountered an error when downloading or the download not being started at all.
  36. /// - `completedResources`: An array of resources that are downloaded and cached successfully.
  37. public typealias PrefetcherProgressBlock =
  38. ((_ skippedResources: [Resource], _ failedResources: [Resource], _ completedResources: [Resource]) -> Void)
  39. /// Progress update block of prefetcher when initialized with a list of resources.
  40. ///
  41. /// - `skippedSources`: An array of sources that are already cached before the prefetching starting.
  42. /// - `failedSources`: An array of sources that fail to be fetched.
  43. /// - `completedResources`: An array of sources that are fetched and cached successfully.
  44. public typealias PrefetcherSourceProgressBlock =
  45. ((_ skippedSources: [Source], _ failedSources: [Source], _ completedSources: [Source]) -> Void)
  46. /// Completion block of prefetcher when initialized with a list of sources.
  47. ///
  48. /// - `skippedResources`: An array of resources that are already cached before the prefetching starting.
  49. /// - `failedResources`: An array of resources that fail to be downloaded. It could because of being cancelled while
  50. /// downloading, encountered an error when downloading or the download not being started at all.
  51. /// - `completedResources`: An array of resources that are downloaded and cached successfully.
  52. public typealias PrefetcherCompletionHandler =
  53. ((_ skippedResources: [Resource], _ failedResources: [Resource], _ completedResources: [Resource]) -> Void)
  54. /// Completion block of prefetcher when initialized with a list of sources.
  55. ///
  56. /// - `skippedSources`: An array of sources that are already cached before the prefetching starting.
  57. /// - `failedSources`: An array of sources that fail to be fetched.
  58. /// - `completedSources`: An array of sources that are fetched and cached successfully.
  59. public typealias PrefetcherSourceCompletionHandler =
  60. ((_ skippedSources: [Source], _ failedSources: [Source], _ completedSources: [Source]) -> Void)
  61. /// `ImagePrefetcher` represents a downloading manager for requesting many images via URLs, then caching them.
  62. /// This is useful when you know a list of image resources and want to download them before showing. It also works with
  63. /// some Cocoa prefetching mechanism like table view or collection view `prefetchDataSource`, to start image downloading
  64. /// and caching before they display on screen.
  65. public class ImagePrefetcher {
  66. /// The maximum concurrent downloads to use when prefetching images. Default is 5.
  67. public var maxConcurrentDownloads = 5
  68. private let prefetchSources: [Source]
  69. private let optionsInfo: KingfisherParsedOptionsInfo
  70. private var progressBlock: PrefetcherProgressBlock?
  71. private var completionHandler: PrefetcherCompletionHandler?
  72. private var progressSourceBlock: PrefetcherSourceProgressBlock?
  73. private var completionSourceHandler: PrefetcherSourceCompletionHandler?
  74. private var tasks = [String: DownloadTask.WrappedTask]()
  75. private var pendingSources: ArraySlice<Source>
  76. private var skippedSources = [Source]()
  77. private var completedSources = [Source]()
  78. private var failedSources = [Source]()
  79. private var stopped = false
  80. // A manager used for prefetching. We will use the helper methods in manager.
  81. private let manager: KingfisherManager
  82. private var finished: Bool {
  83. let totalFinished: Int = failedSources.count + skippedSources.count + completedSources.count
  84. return totalFinished == prefetchSources.count && tasks.isEmpty
  85. }
  86. /// Creates an image prefetcher with an array of URLs.
  87. ///
  88. /// The prefetcher should be initiated with a list of prefetching targets. The URLs list is immutable.
  89. /// After you get a valid `ImagePrefetcher` object, you call `start()` on it to begin the prefetching process.
  90. /// The images which are already cached will be skipped without downloading again.
  91. ///
  92. /// - Parameters:
  93. /// - urls: The URLs which should be prefetched.
  94. /// - options: Options could control some behaviors. See `KingfisherOptionsInfo` for more.
  95. /// - progressBlock: Called every time an resource is downloaded, skipped or cancelled.
  96. /// - completionHandler: Called when the whole prefetching process finished.
  97. ///
  98. /// - Note:
  99. /// By default, the `ImageDownloader.defaultDownloader` and `ImageCache.defaultCache` will be used as
  100. /// the downloader and cache target respectively. You can specify another downloader or cache by using
  101. /// a customized `KingfisherOptionsInfo`. Both the progress and completion block will be invoked in
  102. /// main thread. The `.callbackQueue` value in `optionsInfo` will be ignored in this method.
  103. public convenience init(
  104. urls: [URL],
  105. options: KingfisherOptionsInfo? = nil,
  106. progressBlock: PrefetcherProgressBlock? = nil,
  107. completionHandler: PrefetcherCompletionHandler? = nil)
  108. {
  109. let resources: [Resource] = urls.map { $0 }
  110. self.init(
  111. resources: resources,
  112. options: options,
  113. progressBlock: progressBlock,
  114. completionHandler: completionHandler)
  115. }
  116. /// Creates an image prefetcher with an array of resources.
  117. ///
  118. /// - Parameters:
  119. /// - resources: The resources which should be prefetched. See `Resource` type for more.
  120. /// - options: Options could control some behaviors. See `KingfisherOptionsInfo` for more.
  121. /// - progressBlock: Called every time an resource is downloaded, skipped or cancelled.
  122. /// - completionHandler: Called when the whole prefetching process finished.
  123. ///
  124. /// - Note:
  125. /// By default, the `ImageDownloader.defaultDownloader` and `ImageCache.defaultCache` will be used as
  126. /// the downloader and cache target respectively. You can specify another downloader or cache by using
  127. /// a customized `KingfisherOptionsInfo`. Both the progress and completion block will be invoked in
  128. /// main thread. The `.callbackQueue` value in `optionsInfo` will be ignored in this method.
  129. public convenience init(
  130. resources: [Resource],
  131. options: KingfisherOptionsInfo? = nil,
  132. progressBlock: PrefetcherProgressBlock? = nil,
  133. completionHandler: PrefetcherCompletionHandler? = nil)
  134. {
  135. self.init(sources: resources.map { .network($0) }, options: options)
  136. self.progressBlock = progressBlock
  137. self.completionHandler = completionHandler
  138. }
  139. /// Creates an image prefetcher with an array of sources.
  140. ///
  141. /// - Parameters:
  142. /// - sources: The sources which should be prefetched. See `Source` type for more.
  143. /// - options: Options could control some behaviors. See `KingfisherOptionsInfo` for more.
  144. /// - progressBlock: Called every time an source fetching successes, fails, is skipped.
  145. /// - completionHandler: Called when the whole prefetching process finished.
  146. ///
  147. /// - Note:
  148. /// By default, the `ImageDownloader.defaultDownloader` and `ImageCache.defaultCache` will be used as
  149. /// the downloader and cache target respectively. You can specify another downloader or cache by using
  150. /// a customized `KingfisherOptionsInfo`. Both the progress and completion block will be invoked in
  151. /// main thread. The `.callbackQueue` value in `optionsInfo` will be ignored in this method.
  152. public convenience init(sources: [Source],
  153. options: KingfisherOptionsInfo? = nil,
  154. progressBlock: PrefetcherSourceProgressBlock? = nil,
  155. completionHandler: PrefetcherSourceCompletionHandler? = nil)
  156. {
  157. self.init(sources: sources, options: options)
  158. self.progressSourceBlock = progressBlock
  159. self.completionSourceHandler = completionHandler
  160. }
  161. init(sources: [Source], options: KingfisherOptionsInfo?) {
  162. var options = KingfisherParsedOptionsInfo(options)
  163. prefetchSources = sources
  164. pendingSources = ArraySlice(sources)
  165. // We want all callbacks from our prefetch queue, so we should ignore the callback queue in options.
  166. // Add our own callback dispatch queue to make sure all internal callbacks are
  167. // coming back in our expected queue.
  168. options.callbackQueue = .untouch
  169. optionsInfo = options
  170. let cache = optionsInfo.targetCache ?? .default
  171. let downloader = optionsInfo.downloader ?? .default
  172. manager = KingfisherManager(downloader: downloader, cache: cache)
  173. }
  174. /// Starts to download the resources and cache them. This can be useful for background downloading
  175. /// of assets that are required for later use in an app. This code will not try and update any UI
  176. /// with the results of the process.
  177. public func start() {
  178. guard !stopped else {
  179. assertionFailure("You can not restart the same prefetcher. Try to create a new prefetcher.")
  180. handleComplete()
  181. return
  182. }
  183. guard maxConcurrentDownloads > 0 else {
  184. assertionFailure("There should be concurrent downloads value should be at least 1.")
  185. handleComplete()
  186. return
  187. }
  188. // Empty case.
  189. guard prefetchSources.count > 0 else {
  190. handleComplete()
  191. return
  192. }
  193. let initialConcurrentDownloads = min(prefetchSources.count, maxConcurrentDownloads)
  194. for _ in 0 ..< initialConcurrentDownloads {
  195. if let resource = self.pendingSources.popFirst() {
  196. self.startPrefetching(resource)
  197. }
  198. }
  199. }
  200. /// Stops current downloading progress, and cancel any future prefetching activity that might be occuring.
  201. public func stop() {
  202. if finished { return }
  203. stopped = true
  204. tasks.values.forEach { $0.cancel() }
  205. }
  206. func downloadAndCache(_ source: Source) {
  207. let downloadTaskCompletionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void) = { result in
  208. self.tasks.removeValue(forKey: source.cacheKey)
  209. do {
  210. let _ = try result.get()
  211. self.completedSources.append(source)
  212. } catch {
  213. self.failedSources.append(source)
  214. }
  215. self.reportProgress()
  216. if self.stopped {
  217. if self.tasks.isEmpty {
  218. self.failedSources.append(contentsOf: self.pendingSources)
  219. self.handleComplete()
  220. }
  221. } else {
  222. self.reportCompletionOrStartNext()
  223. }
  224. }
  225. let downloadTask = manager.loadAndCacheImage(
  226. source: source,
  227. options: optionsInfo,
  228. completionHandler: downloadTaskCompletionHandler)
  229. if let downloadTask = downloadTask {
  230. tasks[source.cacheKey] = downloadTask
  231. }
  232. }
  233. func append(cached source: Source) {
  234. skippedSources.append(source)
  235. reportProgress()
  236. reportCompletionOrStartNext()
  237. }
  238. func startPrefetching(_ source: Source)
  239. {
  240. if optionsInfo.forceRefresh {
  241. downloadAndCache(source)
  242. return
  243. }
  244. let cacheType = manager.cache.imageCachedType(
  245. forKey: source.cacheKey,
  246. processorIdentifier: optionsInfo.processor.identifier)
  247. switch cacheType {
  248. case .memory:
  249. append(cached: source)
  250. case .disk:
  251. if optionsInfo.alsoPrefetchToMemory {
  252. _ = manager.retrieveImageFromCache(
  253. source: source,
  254. options: optionsInfo)
  255. {
  256. _ in
  257. self.append(cached: source)
  258. }
  259. } else {
  260. append(cached: source)
  261. }
  262. case .none:
  263. downloadAndCache(source)
  264. }
  265. }
  266. func reportProgress() {
  267. progressSourceBlock?(skippedSources, failedSources, completedSources)
  268. progressBlock?(
  269. skippedSources.compactMap { $0.asResource },
  270. failedSources.compactMap { $0.asResource },
  271. completedSources.compactMap { $0.asResource }
  272. )
  273. }
  274. func reportCompletionOrStartNext() {
  275. if let resource = self.pendingSources.popFirst() {
  276. startPrefetching(resource)
  277. } else {
  278. guard tasks.isEmpty else { return }
  279. handleComplete()
  280. }
  281. }
  282. func handleComplete() {
  283. // The completion handler should be called on the main thread
  284. DispatchQueue.main.safeAsync {
  285. self.completionSourceHandler?(self.skippedSources, self.failedSources, self.completedSources)
  286. self.completionHandler?(
  287. self.skippedSources.compactMap { $0.asResource },
  288. self.failedSources.compactMap { $0.asResource },
  289. self.completedSources.compactMap { $0.asResource }
  290. )
  291. self.completionHandler = nil
  292. self.progressBlock = nil
  293. }
  294. }
  295. }