Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
711 views
in Technique[技术] by (71.8m points)

swift - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...