2016-12-28 54 views
3

我使用SDWebImage库缓存网页中的图像在我UICollectionView:我怎么能得到高速缓存图像的数据SDWebImage

cell.packItemImage.sd_setImage(with: URL(string: smileImageUrl[indexPath.row])) 

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

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

有没有办法让缓存图像一旦从一个URL下载

回答

0

SDWebimage chaches图像数据。基本上它会保存一个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) 
    }) 

不过,如果你想保存图像别的地方或修改也好,你可以在完成块做以上。

7

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

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

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

另外,还要确保你import SDWebImage文件英寸(如果你使用斯威夫特/迦太基,这将是import WebImage

0

SDWebImage已经有此类型的缓存文件的本地

  1. 与您选择的命名空间创建一个SDImageCache
  2. 尝试用imageCache.queryDiskCache获得图像
  3. 如果图像存在,它设置为您的ImageView如果没有,用sd_setImage来获取图像,然后将其保存到本地缓存与SDImageCache.shared().store

的关键通常是图像的URL字符串

这样的事情,可能是不正确的语法:

imageCache.queryDiskCache(forKey: urlForImageString().absoluteString, done: {(_ image: UIImage, _ cacheType: SDImageCacheType) -> Void in 
    if image { 
     self.imageView.image = image 
    } 
    else { 
     self.imageView.sd_setImage(withURL: urlForImageString(), placeholderImage: UIImage(named: "placeholder")!, completed: {(_ image: UIImage, _ error: Error, _ cacheType: SDImageCacheType, _ imageURL: URL) -> Void in 
      SDImageCache.shared().store(image, forKey: urlForImageString().absoluteString) 
     }) 
    } 
})