網路上很多 SDWebImage 的寫法都已經過時了,特別整理這一篇。看完之後,圖片快取基本上就難不倒你了。
第一步:下載 SDWebImage 並匯入工程。GitHub 位址:https://github.com/rs/SDWebImage
第二步:在需要的地方引入標頭檔。
第三步:呼叫 sd_setImageWithURL: 系列方法。注意這是/new/版本的方法名,舊版是 setImageWithURL:。
#import "UIImageView+WebCache.h"
// 1. 最基本的用法
[self.image1 sd_setImageWithURL:imagePath1];
// 2. 帶 completed block,可在圖片載入完成後做事
[self.image2 sd_setImageWithURL:imagePath2 completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
NSLog(@"這裡可以在圖片載入完成之後做些事情");
}];
// 3. 先顯示佔位圖,載入完成後替換
[self.image1 sd_setImageWithURL:imagePath1 placeholderImage:[UIImage imageNamed:@"default"]];
// 4. 佔位圖 + completed block
[self.image1 sd_setImageWithURL:imagePath1
placeholderImage:[UIImage imageNamed:@"default"]
completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
NSLog(@"圖片載入完成後做的事情");
}];
// 5. 加上 options
[self.image1 sd_setImageWithURL:imagePath1
placeholderImage:[UIImage imageNamed:@"default"]
options:SDWebImageRetryFailed];
Objective-C 是自我說明式的語言,看方法名就知道用途,其餘不多贅述。除了帶 options 的方法之外,其他方法都是「記憶體快取 + 磁碟快取」的綜合儲存模式。若只需要記憶體快取,在 options 中指定 SDWebImageCacheMemoryOnly 即可。
如果你不想深入了解,到這裡就已經能用了。接下來說明 options 的所有選項與 SDWebImage 的內部執行流程。
// 失敗後重試 SDWebImageRetryFailed = 1 << 0, // UI 交互期間延遲下載,例如 UIScrollView 減速時 SDWebImageLowPriority = 1 << 1, // 只進行記憶體快取 SDWebImageCacheMemoryOnly = 1 << 2, // 漸進式下載,圖片逐步顯示 SDWebImageProgressiveDownload = 1 << 3, // 刷新快取 SDWebImageRefreshCached = 1 << 4, // 背景中繼續下載 SDWebImageContinueInBackground = 1 << 5, // 處理 cookie SDWebImageHandleCookies = 1 << 6, // 允許使用無效的 SSL 憑證 SDWebImageAllowInvalidSSLCertificates = 1 << 7, // 優先下載 SDWebImageHighPriority = 1 << 8, // 延遲佔位符 SDWebImageDelayPlaceholder = 1 << 9, // 轉換動畫圖片 SDWebImageTransformAnimatedImage = 1 << 10,
入口是 setImageWithURL:placeholderImage:options:,它會先把 placeholderImage 顯示出來,然後由 SDWebImageManager 依 URL 開始處理圖片。
進入 SDWebImageManager 的 download 流程後,交由 SDImageCache 從快取查詢是否已下載過。
第一步:查記憶體快取。若記憶體中已有圖片,SDImageCacheDelegate 回呼 imageCache:didFindImage:forKey:userInfo: 給 SDWebImageManager,再由 SDWebImageManagerDelegate 回呼 webImageManager:didFinishWithImage: 給 UIImageView+WebCache 等前端展示。
第二步:查硬碟快取。若記憶體沒有,會建立一個 NSOperation 加入佇列,在背景執行緒中依 URLKey 於硬碟快取目錄嘗試讀取檔案。讀取完成後回主執行緒 notifyDelegate:。若成功讀到,會把圖片加入記憶體快取(若可用記憶體過小,會先清空記憶體快取),再走一次 didFindImage 的回呼鏈。
第三步:真的沒有才下載。回呼 imageCache:didNotFindImageForKey:userInfo:,接著由 SDWebImageDownloader 開始下載。下載底層用 NSURLConnection,並實作相關 delegate 來判斷下載中、完成與失敗;在 connection:didReceiveData: 中利用 ImageIO 做出隨下載進度遞增的顯示效果。
第四步:解碼。connectionDidFinishLoading: 之後把資料交給 SDWebImageDecoder 做解碼,解碼在獨立的 NSOperationQueue 中完成,不會拖慢主執行緒 UI。如果需要對下載後的圖片做二次處理(例如加浮水印、縮圖),放在這裡效率最好。
第五步:通知與寫入快取。解碼完成後回主執行緒 notifyDelegateOnMainThreadWithInfo:,依序回呼 imageDecoder:didFinishDecodingImage:userInfo:、imageDownloader:didFinishWithImage:,最後通知所有 downloadDelegates 並交由需要的地方展示。同時把圖片寫入 SDImageCache 的記憶體與硬碟快取,寫檔同樣在獨立的 NSOperation 中進行,避免拖慢主執行緒。
其他機制:SDImageCache 初始化時會註冊一些通知,在記憶體警告或 App 退到背景時清理記憶體快取,在 App 結束時清理過期圖片。此外 SDWI 也提供了 UIButton+WebCache 與 MKAnnotationView+WebCache 方便使用;SDWebImagePrefetcher 則可以預先下載圖片,供後續使用。
從上面的流程可以看出,呼叫 setImageWithURL: 時它就自動幫你做了這麼多事。若你需要在某個具體時機插入自己的邏輯,可以直接覆蓋對應環節。例如下載某張圖時要響應進度事件:
// 覆蓋方法,指哪打哪:只在下载 imagePath2 時回應
SDWebImageManager *manager = [SDWebImageManager sharedManager];
[manager downloadImageWithURL:imagePath2
options:SDWebImageRetryFailed
progress:^(NSInteger receivedSize, NSInteger expectedSize) {
NSLog(@"顯示當前進度");
} completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
NSLog(@"下載完成");
}];
對初學者來說,用好 sd_setImageWithURL: 這幾個方法,就足以應付絕大多數的圖片快取需求了。