[英]Save image downloaded using Kingfisher to Document Directory
我正在使用 Kingfisher 从一组 url 下载图像。
我需要将下载或缓存的图像(实际大小的图像)存储在我的文档目录中。
是否有可能做到这一点?
使用以下代码将图像加载到图像视图中。 下载图像后,完成处理程序将帮助执行任何任务。
loadImage(fromUrl: URL(string: imageUrl)!, imageView: imgView, fileName: image.png)
func loadImage(fromUrl: URL, imageView: UIImageView, fileName: String) {
imageView.kf.indicatorType = .activity
imageView.kf.setImage(with:fromUrl, placeholder: nil, options: [.transition(.none)], progressBlock: nil, completionHandler: {(result) in
let documentsDirectoryURL = try! FileManager().url(for:
.documentDirectory, in: .userDomainMask, appropriateFor: nil, create:
true)
let fileURL =
documentsDirectoryURL.appendingPathComponent(fileName)
if !FileManager.default.fileExists(atPath: fileURL.path) {
do {
try UIImagePNGRepresentation(imageView.image!)!.write(to: fileURL)
print("Image Added Successfully")
} catch {
print(error)
}
} else {
print("Image Not Added")
}
})
}
kingfisher现在支持这个操作,你可以这样使用:
let downLoader = ImageDownloader.default
let imageURL = URL(string: "http://xxxx.png")!
downLoader.downloadImage(with: imageURL, completionHandler: { result in
switch result {
case .success(let value):
ImageCache.default.storeToDisk(value.originalData, forKey: "your cache key")
case .failure(let error):
print(error)
}
})
尝试这个:-
let documentsDirectoryURL = try! FileManager().url(for:
.documentDirectory, in: .userDomainMask, appropriateFor: nil, create:
true)
// create a name for your image
let fileURL =
documentsDirectoryURL.appendingPathComponent("imgName.png")
if !FileManager.default.fileExists(atPath: fileURL.path) {
do {
try UIImagePNGRepresentation(cahedimage!)!.write(to: fileURL)
print("Image Added Successfully")
} catch {
print(error)
}
} else {
print("Image Not Added")
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.