LoginSignup
0
1

More than 3 years have passed since last update.

SDWebImage: 特定UIImageViewのキャッシュをクリアする方法

Last updated at Posted at 2020-11-11

はじめに

画像キャッシュライブラリとして広く利用されているSDWebImageですが、
キャッシュをクリアする際のメソッドとして主に以下のメソッドを利用するシーンが多いと思います。

SDImageCache.sharedImageCache().clearMemory()
SDImageCache.sharedImageCache().clearDisk()

しかし特定のUIImageViewのキャッシュをクリアしたい場合には、
いちいちすべてのキャッシュをクリアしてしまうのはコストが高いので、
特定のUIImageViewのキャッシュクリアの方法を調べてみました。

特定のUIImageViewのキャッシュクリア

以下のメソッドを利用することで実現できます。

SDImageCache.shared.removeImageFromDisk(forKey: String)
SDImageCache.shared.removeImageFromDisk(forKey: String)

引数のforKey(cacheKey)とは、そのUIImageViewにセットされているURLのようです。
▼公式ドキュメント

The cache key is an application unique identifier for the image to cache.
It is generally the absolute URL of the image.

generallyが若干気になりますが笑(おそらくキャッシュ時にkeyを指定できるから?)
以下の通り実装することでキャッシュクリアできました。

if let cacheKey = uiimageView.sd_imageURL?.absoluteString {
    SDImageCache.shared.removeImageFromDisk(forKey: cacheKey)
    SDImageCache.shared.removeImageFromDisk(forKey: cacheKey)
}
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1