How to clear AlamofireImage setImageWithURL cache
Hope this might help you:
let URL = NSURL(string: "https://cdn.domain.com/profile/image.jpg")!
let imageDownloader = UIImageView.af_sharedImageDownloader
let imageCache = imageDownloader.imageCache
// Setting CachePolicy as reloadIgnoringLocalCacheData so that it won't use URL Cache next time when it is hitting same URL
let urlRequest = URLRequest(url: URL, cachePolicy: URLRequest.CachePolicy.reloadIgnoringLocalCacheData)
// Clear the Image from the in-memory cache
let _ = imageCache?.removeImage(for: urlRequest, withIdentifier: nil)
imageView.af_setImage(withURLRequest: urlRequest, placeholderImage: UIImage(named: "placeholder"), completion: { (response) in
self.imageView.image = response.result.value
})
Swift3 and AlamofireImage 3.x It appears removeImage does all that is needed.
// Clear what is in the cache, this will force a refresh to ensure fresh image is loaded next time
let urlRequest = Foundation.URLRequest(url: validUrl)
let imageDownloader = UIImageView.af_sharedImageDownloader
if let imageCache2 = imageDownloader.imageCache {
_ = imageCache2.removeImage(for: urlRequest, withIdentifier: nil)
}
You need to remove the image from the in-memory cache as well as the on-disk cache. You can do this as follows:
func clearImageFromCache() {
let URL = NSURL(string: "https://cdn.domain.com/profile/image.jpg")!
let URLRequest = NSURLRequest(URL: URL)
let imageDownloader = UIImageView.af_sharedImageDownloader
// Clear the URLRequest from the in-memory cache
imageDownloader.imageCache?.removeImageForRequest(URLRequest, withAdditionalIdentifier: nil)
// Clear the URLRequest from the on-disk cache
imageDownloader.sessionManager.session.configuration.URLCache?.removeCachedResponseForRequest(URLRequest)
}
Currently, the URLCache
can only be cleared in this manner on the master
branch. I just pushed f35e4748 which allows access to the underlying sessionManager
in the ImageDownloader
. This is not yet available in an actual release yet, but should be here sometime this week.