Cache on self storage (Kingfisher)

Khwan Siricharoenporn
te<h @TDG

--

Hi I will show the solution to cache an image on the Customize storage of Kingfisher. The Customize storage should be created, because when you put the image on the original cache storage Kingfisher will throw some error or incorrect image. This article is too short. You can improve the way of code by yourself. I just posted the code in this article.

Step 1

You must declare the lazy properties target cache of Kingfisher is a global variable.

private lazy var targetCache: ImageCache = {
return ImageCache(name: “new_target_cache”)
}()

Step 2

When you need to store some image into the target cache. You just implement store(image:, original:, forKey: , completionHandler:) the following.

targetCache.store(image, original: nil, forKey: “key_of_image", completionHandler: nil)

Step 3

If you need to get the image that you need. You just implement retrieveImageInDiskCache(forKey:) the following.

targetCache.retrieveImageInDiskCache(forKey: “key_of_image”)

Step 4

If you need to remove the image. You just implement removeImage(forKey:) the following.

targetCache.removeImage(forKey: “key_of_image”)

Step 5

You can download the image with cache parallelly.

KingfisherManager.shared.retrieveImage(with: “URL_OF_IMAGE”, options: [.forceRefresh, .originalCache(targetCache)], progressBlock: nil) { [weak self] (image, _, _, _) in
guard let self = self else { return }
if let image = image {
//Do something
}
}

This is the best solution that you can find. Because you just copy this code and implement it to be suitable for your work.

Thank you~

--

--

Khwan Siricharoenporn
te<h @TDG

iOS Developer @Central Group. Interested about core code, low-level, design pattern and architecture.