概要
SDWebImageを4系から5系にアップデートする必要があったのですが、
ディスクキャッシュを使用しないcacheMemoryOnly
オプションがoptions
から消えたようです。
contextが使えない方向けのピンポイントなマイグレーションガイドです。
経緯
StackOverFlowで秒殺だと思ったのですが、意外に簡潔なSwift用サンプルが見つからず。
公式GitHubで同じ質問をしてる人がいましたが、ちょっと分かりづらい気がしたので記事にしました。
https://github.com/SDWebImage/SDWebImage/issues/2729
一応、issueにある回答としては以下になります。
imageView.sd_setImage(with: url,
placeholderImage: nil,
context: [.storeCacheType : SDImageCacheType.memory.rawValue])
contextに辞書でいれるだけですね。
ただ、ホントにrawValue
まで記載するの?と気になることばかりです。
reference
これだけだとPRを通す根拠に欠けるのでリファレンスを探しました。
SDWebImage - 5.0 Migration guide
SDWebImageOptionsの項目から引用
SDWebImageCacheMemoryOnly removed, use @{SDWebImageContextStoreCacheType : @(SDImageCacheTypeMemory)} context option instead. For Swift user, using [.storeCacheType: SDImageCacheType.memory.rawValue] (rawValue is important, same for other scalar type context option).
冗長に見えますが先程の回答の実装で問題なさそうです。
Migrationつまづきポイント
SDWebImage4系のときのコード▼
imageView.sd_setImage(with: url,
placeholderImage: UIImage(named: "hoge"),
options: [.cacheMemoryOnly, .retryFailed],
completed: {(image, error, ctype, url) in
5系だとこんな感じか?▼
imageView.sd_setImage(with: url,
placeholderImage: UIImage(named: "hoge"),
options: [.retryFailed],
context: [.storeCacheType: SDImageCacheType.memory.rawValue],
completed: {(image, error, ctype, url) in
上記にするとコンパイルエラーで変更案が表示され、従うとcontextがprogressに...
→ progressに辞書を渡してももちろんダメ
原因
ライブラリの中を追えば分かるのですが、UIImageView+WebCache.h
を見ると
sd_setImage()
メソッドは、placeholderImage
, options
, progress
, completed
全ての組み合わせを網羅しているわけではありません。
一番近いオーバーライドが以下だったので、contextがprogressに提案されたのでしょう。
- (void)sd_setImageWithURL:(nullable NSURL *)url
placeholderImage:(nullable UIImage *)placeholder
options:(SDWebImageOptions)options
progress:(nullable SDImageLoaderProgressBlock)progressBlock
completed:(nullable SDExternalCompletionBlock)completedBlock;
以下を利用すれば大丈夫そうですね。
- (void)sd_setImageWithURL:(nullable NSURL *)url
placeholderImage:(nullable UIImage *)placeholder
options:(SDWebImageOptions)options
context:(nullable SDWebImageContext *)context
progress:(nullable SDImageLoaderProgressBlock)progressBlock
completed:(nullable SDExternalCompletionBlock)completedBlock;
修正したコード ▼
imageView.sd_setImage(with: url,
placeholderImage: UIImage(named: "hoge"),
options: [.retryFailed],
context: [.storeCacheType: SDImageCacheType.memory.rawValue],
progress: nil,
completed: {(image, error, ctype, url) in
おわり
完成されたライブラリだと思っていたので、ここにきてなかなかの変更ですね!
SDWebImageのポテンシャルをフル活用するのだけが目的のアプリつくるのも楽しそうですw