ImagePrefetcher.swift 12 KB

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