Kingfisher
Kingfisher copied to clipboard
How to load gif file from Assets
Check List
Thanks for considering to open an issue. Before you submit your issue, please confirm these boxes are checked.
- [x] I have read the wiki page and cheat sheet, but there is no information I need.
- [x] I have searched in existing issues, but did not find a same one.
- [x] I want to report a problem instead of asking a question. It'd better to use kingfisher tag in Stack Overflow to ask a question.
Issue Description
What
I want to use kingfisher load gif from assets, but I can not find any solutions. [Tell us about the issue]
Reproduce
[The steps to reproduce this issue. What is the url you were trying to load, where did you put your code, etc.]
Other Comment
[Add anything else here]
I've ended up doing something like this
import Kingfisher
import UIKit
struct NSDataAssetImageDataProvider: Kingfisher.ImageDataProvider {
let cacheKey: String
let dataAsset: NSDataAsset
init?(name: String, bundle: Bundle = .main) {
guard let dataAsset = NSDataAsset(name: name, bundle: bundle) else { return nil }
self.dataAsset = dataAsset
self.cacheKey = "\(bundle.bundlePath)/\(dataAsset.name).\(dataAsset.typeIdentifier)"
}
func data(handler: @escaping (Result<Data, Error>) -> Void) {
handler(.success(dataAsset.data))
}
}
// somewhere where you want to use it
guard let gifResource = NSDataAssetImageDataProvider(name: "yourDataSetName") else { return }
// I do not cache on disk because reading from assets is faster than reading from disk. Caching to disk will also prevent easy updates of resources because they are cached by path, and there's no way as fas as I know to know if an asset has changed without explicitly changing it's name.
imageView.kf.setImage(
with: gifResource,
options: [.diskCacheExpiration(.expired)]
)