ImagePrefetcher.swift 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  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) 2018 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.
  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 = ((_ skippedResources: [Resource], _ failedResources: [Resource], _ completedResources: [Resource]) -> Void)
  38. /// Completion block of prefetcher.
  39. ///
  40. /// - `skippedResources`: An array of resources that are already cached before the prefetching starting.
  41. /// - `failedResources`: An array of resources that fail to be downloaded. It could because of being cancelled while
  42. /// downloading, encountered an error when downloading or the download not being started at all.
  43. /// - `completedResources`: An array of resources that are downloaded and cached successfully.
  44. public typealias PrefetcherCompletionHandler = ((_ skippedResources: [Resource], _ failedResources: [Resource], _ completedResources: [Resource]) -> Void)
  45. /// `ImagePrefetcher` represents a downloading manager for requesting many images via URLs, then caching them.
  46. /// This is useful when you know a list of image resources and want to download them before showing. It also works with
  47. /// some Cocoa prefetching mechanism like table view or collection view `prefetchDataSource`, to start image downloading
  48. /// and caching before they display on screen.
  49. public class ImagePrefetcher {
  50. /// The maximum concurrent downloads to use when prefetching images. Default is 5.
  51. public var maxConcurrentDownloads = 5
  52. // The dispatch queue to use for handling resource process, so downloading does not occur on the main thread
  53. // This prevents stuttering when preloading images in a collection view or table view.
  54. private var prefetchQueue: DispatchQueue
  55. private let prefetchResources: [Resource]
  56. private let optionsInfo: KingfisherOptionsInfo
  57. private var progressBlock: PrefetcherProgressBlock?
  58. private var completionHandler: PrefetcherCompletionHandler?
  59. private var tasks = [URL: DownloadTask]()
  60. private var pendingResources: ArraySlice<Resource>
  61. private var skippedResources = [Resource]()
  62. private var completedResources = [Resource]()
  63. private var failedResources = [Resource]()
  64. private var stopped = false
  65. // A manager used for prefetching. We will use the helper methods in manager.
  66. private let manager: KingfisherManager
  67. private var finished: Bool {
  68. let totalFinished = failedResources.count + skippedResources.count + completedResources.count
  69. return totalFinished == prefetchResources.count && tasks.isEmpty
  70. }
  71. /// Creates an image prefetcher with an array of URLs.
  72. ///
  73. /// The prefetcher should be initiated with a list of prefetching targets. The URLs list is immutable.
  74. /// After you get a valid `ImagePrefetcher` object, you call `start()` on it to begin the prefetching process.
  75. /// The images which are already cached will be skipped without downloading again.
  76. ///
  77. /// - Parameters:
  78. /// - urls: The URLs which should be prefetched.
  79. /// - options: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
  80. /// - progressBlock: Called every time an resource is downloaded, skipped or cancelled.
  81. /// - completionHandler: Called when the whole prefetching process finished.
  82. ///
  83. /// - Note:
  84. /// By default, the `ImageDownloader.defaultDownloader` and `ImageCache.defaultCache` will be used as
  85. /// the downloader and cache target respectively. You can specify another downloader or cache by using
  86. /// a customized `KingfisherOptionsInfo`. Both the progress and completion block will be invoked in
  87. /// main thread. The `.callbackQueue` value in `optionsInfo` will be ignored in this method.
  88. public convenience init(urls: [URL],
  89. options: KingfisherOptionsInfo? = nil,
  90. progressBlock: PrefetcherProgressBlock? = nil,
  91. completionHandler: PrefetcherCompletionHandler? = nil)
  92. {
  93. let resources: [Resource] = urls.map { $0 }
  94. self.init(resources: resources, options: options, progressBlock: progressBlock, completionHandler: completionHandler)
  95. }
  96. /// Creates an image prefetcher with an array of resources.
  97. ///
  98. /// - Parameters:
  99. /// - resources: The resources which should be prefetched. See `Resource` type for more.
  100. /// - options: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
  101. /// - progressBlock: Called every time an resource is downloaded, skipped or cancelled.
  102. /// - completionHandler: Called when the whole prefetching process finished.
  103. ///
  104. /// - Note:
  105. /// By default, the `ImageDownloader.defaultDownloader` and `ImageCache.defaultCache` will be used as
  106. /// the downloader and cache target respectively. You can specify another downloader or cache by using
  107. /// a customized `KingfisherOptionsInfo`. Both the progress and completion block will be invoked in
  108. /// main thread. The `.callbackQueue` value in `optionsInfo` will be ignored in this method.
  109. public init(resources: [Resource],
  110. options: KingfisherOptionsInfo? = nil,
  111. progressBlock: PrefetcherProgressBlock? = nil,
  112. completionHandler: PrefetcherCompletionHandler? = nil)
  113. {
  114. prefetchResources = resources
  115. pendingResources = ArraySlice(resources)
  116. // Set up the dispatch queue that all our work should occur on.
  117. let prefetchQueueName = "com.onevcat.Kingfisher.PrefetchQueue"
  118. prefetchQueue = DispatchQueue(label: prefetchQueueName)
  119. // We want all callbacks from our prefetch queue, so we should ignore the callback queue in options.
  120. var optionsInfoWithoutQueue = (options ?? .empty)
  121. .removeAllMatchesIgnoringAssociatedValue(.callbackQueue(.untouch))
  122. // Add our own callback dispatch queue to make sure all internal callbacks are
  123. // coming back in our expected queue.
  124. optionsInfoWithoutQueue.append(.callbackQueue(.dispatch(prefetchQueue)))
  125. optionsInfo = optionsInfoWithoutQueue
  126. let cache = optionsInfo.targetCache ?? .default
  127. let downloader = optionsInfo.downloader ?? .default
  128. manager = KingfisherManager(downloader: downloader, cache: cache)
  129. self.progressBlock = progressBlock
  130. self.completionHandler = completionHandler
  131. }
  132. /// Starts to download the resources and cache them. This can be useful for background downloading
  133. /// of assets that are required for later use in an app. This code will not try and update any UI
  134. /// with the results of the process.
  135. public func start()
  136. {
  137. // Since we want to handle the resources cancellation in the prefetch queue only.
  138. prefetchQueue.async {
  139. guard !self.stopped else {
  140. assertionFailure("You can not restart the same prefetcher. Try to create a new prefetcher.")
  141. self.handleComplete()
  142. return
  143. }
  144. guard self.maxConcurrentDownloads > 0 else {
  145. assertionFailure("There should be concurrent downloads value should be at least 1.")
  146. self.handleComplete()
  147. return
  148. }
  149. // Empty case.
  150. guard self.prefetchResources.count > 0 else {
  151. self.handleComplete()
  152. return
  153. }
  154. let initialConcurrentDownloads = min(self.prefetchResources.count, self.maxConcurrentDownloads)
  155. for _ in 0 ..< initialConcurrentDownloads {
  156. if let resource = self.pendingResources.popFirst() {
  157. self.startPrefetching(resource)
  158. }
  159. }
  160. }
  161. }
  162. /// Stops current downloading progress, and cancel any future prefetching activity that might be occuring.
  163. public func stop() {
  164. prefetchQueue.async {
  165. if self.finished { return }
  166. self.stopped = true
  167. self.tasks.values.forEach { $0.cancel() }
  168. }
  169. }
  170. func downloadAndCache(_ resource: Resource) {
  171. let downloadTaskCompletionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void) = { result in
  172. self.tasks.removeValue(forKey: resource.downloadURL)
  173. if let _ = result.error {
  174. self.failedResources.append(resource)
  175. } else {
  176. self.completedResources.append(resource)
  177. }
  178. self.reportProgress()
  179. if self.stopped {
  180. if self.tasks.isEmpty {
  181. self.failedResources.append(contentsOf: self.pendingResources)
  182. self.handleComplete()
  183. }
  184. } else {
  185. self.reportCompletionOrStartNext()
  186. }
  187. }
  188. let downloadTask = manager.downloadAndCacheImage(
  189. with: resource.downloadURL,
  190. forKey: resource.cacheKey,
  191. options: optionsInfo,
  192. progressBlock: nil,
  193. completionHandler: downloadTaskCompletionHandler)
  194. if let downloadTask = downloadTask {
  195. tasks[resource.downloadURL] = downloadTask
  196. }
  197. }
  198. func append(cached resource: Resource) {
  199. skippedResources.append(resource)
  200. reportProgress()
  201. reportCompletionOrStartNext()
  202. }
  203. func startPrefetching(_ resource: Resource)
  204. {
  205. if optionsInfo.forceRefresh {
  206. downloadAndCache(resource)
  207. } else {
  208. let alreadyInCache = manager.cache.imageCachedType(
  209. forKey: resource.cacheKey,
  210. processorIdentifier: optionsInfo.processor.identifier).cached
  211. if alreadyInCache {
  212. append(cached: resource)
  213. } else {
  214. downloadAndCache(resource)
  215. }
  216. }
  217. }
  218. func reportProgress() {
  219. progressBlock?(skippedResources, failedResources, completedResources)
  220. }
  221. func reportCompletionOrStartNext() {
  222. prefetchQueue.async {
  223. if let resource = self.pendingResources.popFirst() {
  224. self.startPrefetching(resource)
  225. } else {
  226. guard self.tasks.isEmpty else { return }
  227. self.handleComplete()
  228. }
  229. }
  230. }
  231. func handleComplete() {
  232. // The completion handler should be called on the main thread
  233. DispatchQueue.main.safeAsync {
  234. self.completionHandler?(self.skippedResources, self.failedResources, self.completedResources)
  235. self.completionHandler = nil
  236. self.progressBlock = nil
  237. }
  238. }
  239. }