31

I have all images loaded on my app via SDWebImage. The downloading and caching works great, but I wanted to make a button that can clear all cached images in the entire app.

I have a "Clear Cache" button as a UIButton on one of my tab bar views. How can I make it so when this button is tapped, all the cached images are removed and need to be re-downloaded?

Using Swift.

Thank you!

Miles
  • 625
  • 2
  • 9
  • 18

5 Answers5

68

If you want to completely clear the cache do the following:

Obj-c:

- (IBAction)clearCache:(id)sender {
    [[SDImageCache sharedImageCache]clearMemory];
    [[SDImageCache sharedImageCache]clearDisk];
}

Swift 5

SDImageCache.shared.clearMemory()
SDImageCache.shared.clearDisk()

Swift 3.0

@IBAction func clearCache(sender: UIButton) {
    SDImageCache.shared().clearMemory()
    SDImageCache.shared().clearDisk()
}
Zorayr
  • 23,770
  • 8
  • 136
  • 129
guidev
  • 2,695
  • 2
  • 23
  • 44
2

Try this:

@IBAction func actClearCache(sender:AnyObject) {

   let objCache = SDImageCache.sharedImageCache()
   objCache.clearMemory()
   objCache.cleanDisk()

}
Bista
  • 7,869
  • 3
  • 27
  • 55
  • Thanks for the response. How can I link this up to a UIButton? Would it be through an outlet? – Miles Oct 05 '16 at 18:58
  • Got it, thanks! I am getting an error that says: Use of unresolved identifier 'SDImageCache'. Would I need to import it in my bridging header? – Miles Oct 05 '16 at 19:05
  • Have you ‘import SDWebImage`? And which swift version are you using? – Bista Oct 05 '16 at 19:06
  • Here's my bridging header: #import "SDWebImage/UIImageView+WebCache.h" #import "SDWebImane" It says that 'SdWebImane' file not found – Miles Oct 05 '16 at 19:12
  • I imported SDWebImage, and I think I'm using Swift 2.2 – Miles Oct 05 '16 at 19:20
  • I didn't write "import SDWebImage" on the .swift file attached to the View controller. It works now that I've wrote it! – Miles Oct 05 '16 at 20:41
  • As of this date cleanDisk and clearDisk are missing from SDImageCache.h. But they're still in http://cocoadocs.org/docsets/SDWebImage/3.3/Classes/SDImageCache.html#//api/name/clearDisk – Bob Lissner Apr 01 '18 at 20:45
1

Swift 4.2 , Xcode 10

pod 'SDWebImage', '5.0.0-beta3'

import SDWebImage

 @IBAction func ClearCacheButtonClick(_ sender: UIButton) {
     SDImageCache.shared.clearMemory()
     SDImageCache.shared.clearDisk()
 }
Vishal Vaghasiya
  • 4,618
  • 3
  • 29
  • 40
1

To delete all data from cache

SDImageCache.shared.clear(with: .all) {
    print("Disk & memory data cleared")
}

To delete data from only memory

SDImageCache.shared.clear(with: .memory) {
    print("Memory data cleared")
}

To delete data from disk

SDImageCache.shared.clear(with: .disk) {
    print("Disk data cleared")
}
Abdullah
  • 21
  • 7
0

Swift 5

import SDWebImage

  SDImageCache.shared.clearMemory()

  SDImageCache.shared.clearDisk()