2 // ImagePrefetcher.swift
5 // Created by Claire Knight <claire.knight@moggytech.co.uk> on 24/02/2016
7 // Copyright (c) 2018 Wei Wang <onevcat@gmail.com>
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:
16 // The above copyright notice and this permission notice shall be included in
17 // all copies or substantial portions of the Software.
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
35 /// Progress update block of prefetcher.
37 /// - `skippedResources`: An array of resources that are already cached before the prefetching starting.
38 /// - `failedResources`: An array of resources that fail to be downloaded. It could because of being cancelled while downloading, encountered an error when downloading or the download not being started at all.
39 /// - `completedResources`: An array of resources that are downloaded and cached successfully.
40 public typealias PrefetcherProgressBlock = ((_ skippedResources: [Resource], _ failedResources: [Resource], _ completedResources: [Resource]) -> Void)
42 /// Completion block of prefetcher.
44 /// - `skippedResources`: An array of resources that are already cached before the prefetching starting.
45 /// - `failedResources`: An array of resources that fail to be downloaded. It could because of being cancelled while downloading, encountered an error when downloading or the download not being started at all.
46 /// - `completedResources`: An array of resources that are downloaded and cached successfully.
47 public typealias PrefetcherCompletionHandler = ((_ skippedResources: [Resource], _ failedResources: [Resource], _ completedResources: [Resource]) -> Void)
49 /// `ImagePrefetcher` represents a downloading manager for requesting many images via URLs, then caching them.
50 /// This is useful when you know a list of image resources and want to download them before showing.
51 public class ImagePrefetcher {
53 /// The maximum concurrent downloads to use when prefetching images. Default is 5.
54 public var maxConcurrentDownloads = 5
56 private let prefetchResources: [Resource]
57 private let optionsInfo: KingfisherOptionsInfo
58 private var progressBlock: PrefetcherProgressBlock?
59 private var completionHandler: PrefetcherCompletionHandler?
61 private var tasks = [URL: RetrieveImageDownloadTask]()
63 private var pendingResources: ArraySlice<Resource>
64 private var skippedResources = [Resource]()
65 private var completedResources = [Resource]()
66 private var failedResources = [Resource]()
68 private var stopped = false
70 // The created manager used for prefetch. We will use the helper method in manager.
71 private let manager: KingfisherManager
73 private var finished: Bool {
74 return failedResources.count + skippedResources.count + completedResources.count == prefetchResources.count && self.tasks.isEmpty
78 Init an image prefetcher with an array of URLs.
80 The prefetcher should be initiated with a list of prefetching targets. The URLs list is immutable.
81 After you get a valid `ImagePrefetcher` object, you could call `start()` on it to begin the prefetching process.
82 The images already cached will be skipped without downloading again.
84 - parameter urls: The URLs which should be prefetched.
85 - parameter options: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
86 - parameter progressBlock: Called every time an resource is downloaded, skipped or cancelled.
87 - parameter completionHandler: Called when the whole prefetching process finished.
89 - returns: An `ImagePrefetcher` object.
91 - Note: By default, the `ImageDownloader.defaultDownloader` and `ImageCache.defaultCache` will be used as
92 the downloader and cache target respectively. You can specify another downloader or cache by using a customized `KingfisherOptionsInfo`.
93 Both the progress and completion block will be invoked in main thread. The `CallbackDispatchQueue` in `optionsInfo` will be ignored in this method.
95 public convenience init(urls: [URL],
96 options: KingfisherOptionsInfo? = nil,
97 progressBlock: PrefetcherProgressBlock? = nil,
98 completionHandler: PrefetcherCompletionHandler? = nil)
100 let resources: [Resource] = urls.map { $0 }
101 self.init(resources: resources, options: options, progressBlock: progressBlock, completionHandler: completionHandler)
105 Init an image prefetcher with an array of resources.
107 The prefetcher should be initiated with a list of prefetching targets. The resources list is immutable.
108 After you get a valid `ImagePrefetcher` object, you could call `start()` on it to begin the prefetching process.
109 The images already cached will be skipped without downloading again.
111 - parameter resources: The resources which should be prefetched. See `Resource` type for more.
112 - parameter options: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
113 - parameter progressBlock: Called every time an resource is downloaded, skipped or cancelled.
114 - parameter completionHandler: Called when the whole prefetching process finished.
116 - returns: An `ImagePrefetcher` object.
118 - Note: By default, the `ImageDownloader.defaultDownloader` and `ImageCache.defaultCache` will be used as
119 the downloader and cache target respectively. You can specify another downloader or cache by using a customized `KingfisherOptionsInfo`.
120 Both the progress and completion block will be invoked in main thread. The `CallbackDispatchQueue` in `optionsInfo` will be ignored in this method.
122 public init(resources: [Resource],
123 options: KingfisherOptionsInfo? = nil,
124 progressBlock: PrefetcherProgressBlock? = nil,
125 completionHandler: PrefetcherCompletionHandler? = nil)
127 prefetchResources = resources
128 pendingResources = ArraySlice(resources)
130 // We want all callbacks from main queue, so we ignore the call back queue in options
131 let optionsInfoWithoutQueue = options?.removeAllMatchesIgnoringAssociatedValue(.callbackDispatchQueue(nil))
132 self.optionsInfo = optionsInfoWithoutQueue ?? KingfisherEmptyOptionsInfo
134 let cache = self.optionsInfo.targetCache
135 let downloader = self.optionsInfo.downloader
136 manager = KingfisherManager(downloader: downloader, cache: cache)
138 self.progressBlock = progressBlock
139 self.completionHandler = completionHandler
143 Start to download the resources and cache them. This can be useful for background downloading
144 of assets that are required for later use in an app. This code will not try and update any UI
145 with the results of the process.
149 // Since we want to handle the resources cancellation in main thread only.
150 DispatchQueue.main.safeAsync {
152 guard !self.stopped else {
153 assertionFailure("You can not restart the same prefetcher. Try to create a new prefetcher.")
154 self.handleComplete()
158 guard self.maxConcurrentDownloads > 0 else {
159 assertionFailure("There should be concurrent downloads value should be at least 1.")
160 self.handleComplete()
164 guard self.prefetchResources.count > 0 else {
165 self.handleComplete()
169 let initialConcurentDownloads = min(self.prefetchResources.count, self.maxConcurrentDownloads)
170 for _ in 0 ..< initialConcurentDownloads {
171 if let resource = self.pendingResources.popFirst() {
172 self.startPrefetching(resource)
180 Stop current downloading progress, and cancel any future prefetching activity that might be occuring.
183 DispatchQueue.main.safeAsync {
184 if self.finished { return }
186 self.tasks.values.forEach { $0.cancel() }
190 func downloadAndCache(_ resource: Resource) {
192 let downloadTaskCompletionHandler: CompletionHandler = { (image, error, _, _) -> Void in
193 self.tasks.removeValue(forKey: resource.downloadURL)
195 self.failedResources.append(resource)
197 self.completedResources.append(resource)
200 self.reportProgress()
202 if self.tasks.isEmpty {
203 self.failedResources.append(contentsOf: self.pendingResources)
204 self.handleComplete()
207 self.reportCompletionOrStartNext()
211 let downloadTask = manager.downloadAndCacheImage(
212 with: resource.downloadURL,
213 forKey: resource.cacheKey,
214 retrieveImageTask: RetrieveImageTask(),
216 completionHandler: downloadTaskCompletionHandler,
217 options: optionsInfo)
219 if let downloadTask = downloadTask {
220 tasks[resource.downloadURL] = downloadTask
224 func append(cached resource: Resource) {
225 skippedResources.append(resource)
228 reportCompletionOrStartNext()
231 func startPrefetching(_ resource: Resource)
233 if optionsInfo.forceRefresh {
234 downloadAndCache(resource)
236 let alreadyInCache = manager.cache.imageCachedType(forKey: resource.cacheKey,
237 processorIdentifier: optionsInfo.processor.identifier).cached
239 append(cached: resource)
241 downloadAndCache(resource)
246 func reportProgress() {
247 progressBlock?(skippedResources, failedResources, completedResources)
250 func reportCompletionOrStartNext() {
251 DispatchQueue.main.async {
252 if let resource = self.pendingResources.popFirst() {
253 self.startPrefetching(resource)
255 guard self.tasks.isEmpty else { return }
256 self.handleComplete()
261 func handleComplete() {
262 completionHandler?(skippedResources, failedResources, completedResources)
263 completionHandler = nil