Kingfisher icon indicating copy to clipboard operation
Kingfisher copied to clipboard

How to load gif file from Assets

Open leroyli opened this issue 1 year ago • 1 comments

Check List

Thanks for considering to open an issue. Before you submit your issue, please confirm these boxes are checked.

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]

leroyli avatar Sep 01 '23 10:09 leroyli

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)]
)

japanese-goblinn avatar Sep 06 '23 12:09 japanese-goblinn