How to clear AlamofireImage setImageWithURL cache

被刻印的时光 ゝ 提交于 2019-11-28 08:36:54

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.

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)
        }

My solution for the caching issue:

func af_setImageIgnoreCache(string: String?) {
  guard let url = string, let nsurl = URL(string: url) else { return }
  let urlRequest = URLRequest(url: nsurl, cachePolicy: .reloadIgnoringCacheData)

  let imageDownloader = ImageDownloader.default
  if let imageCache = imageDownloader.imageCache as? AutoPurgingImageCache, let urlCache = imageDownloader.sessionManager.session.configuration.urlCache {
    _ = imageCache.removeImages(matching: urlRequest)
    urlCache.removeCachedResponse(for: urlRequest)
  }

  af_setImage(withURLRequest: urlRequest)
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!