如何获取缓存图像SDWebImage的数据

Taw*_*bid 7 ios sdwebimage swift

我正在使用SDWebImage库来缓存我的UICollectionView中的Web图像:

cell.packItemImage.sd_setImage(with: URL(string: smileImageUrl[indexPath.row]))
Run Code Online (Sandbox Code Playgroud)

但我想将缓存的图像本地保存在文件中,而不是再次下载它们

FileManager.default.createFile(atPath: newPath, contents: Data(contentsOf:  URL(string: snapchildvalue[Constants.smiles.smileImageUrl] as! String)!), attributes: nil)
Run Code Online (Sandbox Code Playgroud)

有没有办法获取缓存图像的数据

Kaa*_*glu 20

SDWebImage默认情况下自动缓存下载的图像.您可以使用SDImageCache从缓存中检索图像.当前应用会话有一个内存缓存,它会更快,并且有磁盘缓存.用法示例:

if let image = SDImageCache.shared().imageFromDiskCache(forKey: imageURL.absoluteString) {
//use image
}

if let image = SDImageCache.shared().imageFromMemoryCache(forKey: imageURL.absoluteString) {
//use image
}
Run Code Online (Sandbox Code Playgroud)

还要确保你import SDWebImage的文件.(如果你使用的是Swift/Carthage,那就是import WebImage


Saa*_*aad 5

一旦从 URL 下载图像,SDWebimage 就会对其进行缓存。基本上,它会根据 URL 保存图像,并且下次如果图像可用于 URL。它只会从缓存中获取该图像。因此,如果图像已经下载到设备,将立即调用以下方法。

    imgView.sd_setImage(with: URL(string:url), completed: { (image, error, type, url) in
         imgView.image = image
         //Do any thing with image here. This will be called instantly after image is downloaded to cache. E.g. if you want to save image (Which is not required for a simple image fetch, 
         //you can use FileManager.default.createFile(atPath: newPath, contents: UIImagePNGRepresentation(image), attributes: nil)
     })
Run Code Online (Sandbox Code Playgroud)

不过,如果您想将该图像保存在其他地方或修改它或其他什么,您可以在上面的完成块中完成。