How to put image into AutoPurgingImageCache after

2019-06-05 02:48发布

I want to use imageView.af_setImageWithURL(URL) together with the AutoPurgingImageCache from AlamofireImage.

How can I be informed that af_setImageWithURL fetched the image, so I can put it into my cache? Because this is done in Background.

I'd prefer something like: imageView.af_imageFromCache(URL) which sets the image from cache if it is already in there or otherwise downloads async, then sets the image and saves it in the cache.

2条回答
劫难
2楼-- · 2019-06-05 03:21

The shared ImageDownloader that the UIImageView uses already puts the image into the AutoPurgingImageCache automatically. Every time you use the imageView.af_setImageWithURL(URL) it will attempt to pull the image out of the image cache if it exists. If the image is not already in the cache, it will start the download on the ImageDownloader instance.

查看更多
Summer. ? 凉城
3楼-- · 2019-06-05 03:28

SWIFT 4.0

Set 'AutoPurgingImageCache' in Appdelegate so that i can access it in any class

var imageCache:AutoPurgingImageCache?

   imageCache = AutoPurgingImageCache(
        memoryCapacity: 100_000_000,
        preferredMemoryUsageAfterPurge: 60_000_000
    )

Then set image in my service class

class func setImage(url : String,imageview:UIImageView) {

    let imageCache = appDelegate.imageCache!
    // Fetch
    if let cachedAvatar = imageCache.image(withIdentifier: url){
         imageview.image = cachedAvatar
    }else {

        Alamofire.request(url).responseImage { response in
            debugPrint(response)
            debugPrint(response.result)
            if let image = response.result.value {
                imageview.image = image
                // Add
                imageCache.add(image, withIdentifier: url)
            }
        }
    }
}
查看更多
登录 后发表回答