Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to clear AlamofireImage setImageWithURL cache

I am using AlamofireImage in my project quite a lot and I use

let URL = NSURL(string: "https://cdn.domain.com/profile/image.jpg")!
imageView.af_setImageWithURL(URL)

to fetch an image from my CDN. I have done some tests but correct me if I am wrong, this seems to store the downloaded image in to a cache. My tests included downloading a 5mb image. The first time it took about 20 seconds, the second time was instant.

The thing I would like to know is how can I clear the cache for a specific URL/image and re-download the image?

Say for example I update a users profile pic. The image name/URL will be exactly the same but I know the image has changes as the user selected a new image from their library or camera. I know the image has been uploaded successfully to the CDN as I can see the new image in the folder directly on the CDN.

like image 899
puks1978 Avatar asked Nov 01 '15 21:11

puks1978


1 Answers

Swift 5:

func clearImageCache(forUrl urlString: String) {
    guard let url = URL(string: urlString) else {
        return
    }
    let imageDownloader = UIImageView.af_sharedImageDownloader
    let urlRequest = URLRequest(url: url)
    // Clear the URLRequest from the in-memory cache
    _ = imageDownloader.imageCache?.removeImage(for: urlRequest, withIdentifier: nil)
    // Clear the URLRequest from the on-disk cache
    imageDownloader.session.sessionConfiguration.urlCache?.removeCachedResponse(for: urlRequest)
}
like image 133
Dmitry Avatar answered Sep 25 '22 15:09

Dmitry