问题
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.
回答1:
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.
回答2:
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)
}
}
}
}
来源:https://stackoverflow.com/questions/33278487/how-to-put-image-into-autopurgingimagecache-after-af-setimagewithurl-completed