0

So I have a UIButton whose imageView is set to an image using a download URL. For this purpose I use SDWebImage.

Problem is, when I press the delete button, I want the image to completely disappear but I guess it does not work because the image is still being retrieved from cache. How do I solve this?

class ViewController: UIViewController{

    var profileButton: UIButton = {
        let button = UIButton(type: .system)
        return button
    }()

    var user: User?

    override func viewDidLoad() {
        super.viewDidLoad()
        view.addSubview(profileButton)
        profileButton.addTarget(self, action: #selector(handleDelete), for: .touchUpInside)

        self.loadUserPhotos()
    }

    fileprivate func loadUserPhotos(){
        let profileImageUrl = self.user?.profileImageUrl1
        if let imageUrl = profileImageUrl, let url = URL(string: imageUrl){
            SDWebImageManager.shared().loadImage(with: url, options: .continueInBackground, progress: nil) { (image, _, _, _, _, _) in
                self.profileButton.setImage(image?.withRenderingMode(.alwaysOriginal), for: .normal)
            }
        }
    }

    @objc func handleDelete(){
        self.user?.profileImageUrl1 = ""
        self.profileButton.imageView?.image = nil
        self.loadUserPhotos()
    }
}
Archid
  • 377
  • 6
  • 21
  • Does this answer your question? [How to clear all cached images loaded from SDWebImage?](https://stackoverflow.com/questions/39881566/how-to-clear-all-cached-images-loaded-from-sdwebimage) – dahiya_boy Feb 26 '20 at 13:20

2 Answers2

1

To remove the image from UIButton you need to mention the state as well.

self.profileButton.setImage(nil, for: .normal)
sanjeev
  • 150
  • 3
  • This worked. Didn't have to do the extra step of clearing the cache. I guess SDWEB handles this on its own or does it? – Archid Feb 26 '20 at 13:36
  • You are setting the image to nil in button while the image lies in cache. You need not have to delete cache for this. – Manav Feb 26 '20 at 13:49
1

You can use :

SDImageCache.shared.removeImage(forKey: url?.description, withCompletion: nil)
Manav
  • 2,284
  • 1
  • 14
  • 27