How to ignore or overwrite UIImage cache in swift when I uploaded new image to server?

Viewed 147

I want to let URL image update immediately when I uploaded new image, but it always display previous uploaded image.

func changeUserIMG(imgURL:String){

    if let url = URL(string: imgURL) {

        URLSession.shared.dataTask(with: url, completionHandler: {(data,responds,error) in
            if error != nil{
                print(error!.localizedDescription)
            }
            else if let imageData = data{
                DispatchQueue.main.async {
                    self.userImage.image = UIImage(data: imageData)
                }
            }
        }).resume()

    }
}

Is there anyway to overwrite or ignore UIImage chache?

edit:

func changeUserIMG(imgURL:String){

    if let url = URL(string: imgURL) {

        let request = URLRequest.init(url: url, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 60)
        URLSession.shared.dataTask(with: request,completionHandler: {(data,responds,error) in
            if error != nil{
                print(error!.localizedDescription)
            }else{
                DispatchQueue.main.async {
                    self.userImage.image = UIImage(data: data!)
                }
            }
        }).resume()

}

Even I try to use .reloadIgnoringLocalCacheData, still display previous uploaded image.

Where's the problem?

2 Answers

I found some ways you can clear the URLSession cache:

1) Replacing URLSession.shared with URLSession(configuration: URLSessionConfiguration.ephemeral)

2) Adding this method before reloading the data: URLCache.shared.removeAllCachedResponses()

Combing your problem, the same url is different from the picture, causing you to always use the old picture. The effect you want is that when the server uploads a new image, the client can immediately display the new image.

You can try these points.

  1. If you want to display the latest image immediately, you must notify the client to refresh the page when the upload is complete.

  2. I think you could try a picture corresponding to a url, so as to avoid dealing with unnecessary caching problems.

Related