Search code examples
iosimage-cachingkingfisher

Backup and restore Kingfisher image cache


Using Kingfisher, I want to ship a pre-seeded image cache with my application bundle, so my app can function offline, while still able to fetch future images that weren't shipped with the app.

I used KingfisherManager.shared.retrieveImage(with: url, completionHandler: nil) to download and cache all the desired images. Then I backed up the contents of Library/Caches/com.onevcat.Kingfisher.ImageCache.default and archived to my application bundle. On first app run, I restore the cache to the original location.

But this doesn't seem to work. ImageCache.default.isCached(forKey: url) returns false and no images are displayed while offline. If I fetch the images again while online, afterwards the files in Library/Caches/com.onevcat.Kingfisher.ImageCache.default are identical binaries with fresh modified dates, indicating they were touched, but no difference in the cache's contents.

Is there some other state Kingfisher stores somewhere that I need to backup and restore? I haven't been able to identify anything else in the other files in the application sandbox.


Solution

  • I figured this out. Kingfisher uses the cached files' modificationDate as an expiration date. When copying the cache, the file creation and modification dates are both set to the current time, which is then in the past and considered expired when Kingfisher attempts to load an image.

    I resolved this by setting the modification date to distantFuture after copying the files, as I don't want the cache to ever expire.