SwiftUI中无法为KFImage设置自定义缓存问题求助
在SwiftUI中为KFImage配置自定义"offline"缓存
我想在SwiftUI视图里用名为“offline”的自定义缓存加载KFImage,试了多种方法都没成功,但在UIKit里这个功能正常工作。
缓存说明
- Default:通用用途缓存,内存和磁盘缓存数小时后过期
- Offline:用于需要永久保存在磁盘,或直到恢复网络并成功将图片上传至数据库的图片
当前SwiftUI代码
let url = URL(string: item.photoURL ?? "") ?? URL(string: "")! let resource: ImageResource = ImageResource(downloadURL: url, cacheKey: item.photoURL) KFImage(source: .network(resource)) .resizable() .aspectRatio(contentMode: .fill) .clipped() .progressViewStyle(.linear) .frame(width: size, height: size)
可正常工作的UIKit代码
capturedImageView.kf.setImage(with: imageURL, placeholder: nil, options: [ .scaleFactor(UIScreen.main.scale), .transition(.fade(0.25)), .targetCache(ImageCache(name: "offline")), ])
解决方案
SwiftUI版的KFImage可以通过setOptions()修饰符传入配置选项,和UIKit的参数逻辑一致。只需要添加这个修饰符并传入.targetCache选项即可绑定自定义缓存:
// 先创建自定义缓存实例 let offlineCache = ImageCache(name: "offline") // 修改后的KFImage使用代码 let url = URL(string: item.photoURL ?? "") ?? URL(string: "")! let resource: ImageResource = ImageResource(downloadURL: url, cacheKey: item.photoURL) KFImage(source: .network(resource)) .setOptions([ .scaleFactor(UIScreen.main.scale), .transition(.fade(0.25)), .targetCache(offlineCache) ]) .resizable() .aspectRatio(contentMode: .fill) .clipped() .progressViewStyle(.linear) .frame(width: size, height: size)
原理说明:setOptions()是Kingfisher为SwiftUI封装的修饰符,用来传递各种加载配置,其中.targetCache选项可以指定使用自定义缓存实例,和UIKit中的对应参数功能完全一致。
内容的提问来源于stack exchange,提问作者Emin Israfil iOS
相关产品推荐
相关产品推荐

