SDWebImage ReadMe.md 文檔
附
:SDWebImage框架github下載地址:https://github.com/rs/SDWebImage注1
:該文章簡單翻譯了SDWebImage最新版本(3.7.5)的readMe.md,時間緊促,如有不當請指正修改,十分感激。注2
:對該框架的學習將持續進行,在個人的github地址可以得到最新進展。
Web Image
版本3.7.5
|平台iOS
|開源協議MIT
|
該庫為UIImageView提供了一個分類來處理遠程圖片資源的加載。
它:
1)為Cocoa Touch框架提供一個UIImageView的分類,加載圖片並進行緩存處理。 2)異步圖像下載 3)異步存儲器+具備自動緩存過期處理的磁盤映像緩存 4)支持GIF播放 5)支持WebP格式 6)背景圖像解壓縮 7)保證同一個url圖片資源不被多次下載 8)保證錯誤url不被反復嘗試下載 9)保證不會阻塞主線程 10)高性能 11)使用GCD和ARC 12)支持Arm64架構
注
:SDWebimage3.0版本並沒有完全向后兼容2.0版本且要求的最低配置為iOS5.1.1版本。如果你需要在iOS5.0以前的版本使用,那么請您使用2.0版本。
How is SDWebImage better than X?
·AFNetworking已經提供UIImageView相似的功能,還有必要使用SDWebimage嗎?
Who Use It(誰用)
查看哪些應用使用了SDWebImage框架,添加你的應用到列表。
How To Use(如何用)
查看api文檔CocoaDocs - SDWebImage
TableView加載圖片使用UIImageView+WebCache分類
只需要包含UIImageView+WebCache.h頭文件,並在tableView的數據源方法tableView:cellForRowAtIndexPath: 中調用sd_setImageWithURL:placeholderImage:方法即可。異步下載和緩存處理這一切都將會自動為你處理。
#import <SDWebImage/UIImageView+WebCache.h> ... - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *MyIdentifier = @"MyIdentifier"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MyIdentifier] autorelease]; } // Here we use the new provided sd_setImageWithURL: method to load the web image [cell.imageView sd_setImageWithURL:[NSURL URLWithString:@"http://www.domain.com/path/to/image.jpg"] placeholderImage:[UIImage imageNamed:@"placeholder.png"]]; cell.textLabel.text = @"My Text"; return cell; }
使用Blocks
使用block,你將能夠得到圖片的下載進度並獲知圖片是否下載成功或者失敗:
// Here we use the new provided sd_setImageWithURL: method to load the web image [cell.imageView sd_setImageWithURL:[NSURL URLWithString:@"http://www.domain.com/path/to/image.jpg"] placeholderImage:[UIImage imageNamed:@"placeholder.png"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) { ... completion code here ... }];
注意
:如果圖像請求在完成前被取消了,那么成功和失敗的block塊將都不會被調用。
使用SDWebImageManager
UIImageView+WebCache分類背后調用的是SDWebImageManager類的方法,負責圖像的異步下載和緩存處理。你可以直接使用這個類來下載圖片和進行緩存處理。
這有一個如何使用SDWebImageManager的簡單示例:
SDWebImageManager *manager = [SDWebImageManager sharedManager];
[manager downloadImageWithURL:imageURL
options:0 progress:^(NSInteger receivedSize, NSInteger expectedSize) { // progression tracking code } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) { if (image) { // do something with image } }];
單獨異步下載圖片
它也可以獨立使用異步圖片下載:
SDWebImageDownloader *downloader = [SDWebImageDownloader sharedDownloader];
[downloader downloadImageWithURL:imageURL
options:0 progress:^(NSInteger receivedSize, NSInteger expectedSize) { // progression tracking code } completed:^(UIImage *image, NSData *data, NSError *error, BOOL finished) { if (image && finished) { // do something with image } }];
單獨異步緩存圖片
也可以單獨使用基於圖像的高速異步緩存處理。SDImagecache提供內存高速緩存和可選的磁盤高速緩存。磁盤高速緩存寫入操作是異步的,所以不需要在用戶界面添加不必要的延遲。
為了方便,SDImageCache類提供了一個單一的實例,但如果你想自定義緩存空間,那么可以創建自己的實例。
您可以使用queryDiskCacheForKey:done:
方法查找緩存。如果該方法返回nil,則說明當前image沒有緩存。你需要負責下載和進行緩存處理。圖像緩存的key通常為該圖像的URL。
SDImageCache *imageCache = [[SDImageCache alloc] initWithNamespace:@"myNamespace"]; [imageCache queryDiskCacheForKey:myCacheKey done:^(UIImage *image) { // image is not nil if image was found }];
默認情況下,如果對應圖片的內存緩存不存在,那么SDImageCache將查找磁盤緩存。可以通過調用imageFromMemoryCacheForKey:
方法來阻止。
你可以調用storeImage:forKey: method:
方法保存圖片到緩存。
[[SDImageCache sharedImageCache] storeImage:myImage forKey:myCacheKey];
默認情況下,圖像將被進行內存緩存和磁盤緩存(異步)。如果你只想要內存緩存,那么可以使用storeImage:forKey:toDisk:方法,第三個參數傳NO即可。
使用緩存key篩選器
有時,你可能會因為URL的一部分是動態的而不希望使用URL作為圖像緩存的key。 SDWebImageManager提供了一種方式來設置,輸入URL輸出對應的字符串。
下面的示例在應用程序的委托中設置一個過濾器,在使用它的緩存鍵之前將從URL中刪除任何查詢字符串
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { SDWebImageManager.sharedManager.cacheKeyFilter = ^(NSURL *url) { url = [[NSURL alloc] initWithScheme:url.scheme host:url.host path:url.path]; return [url absoluteString]; }; // Your app init code... return YES; }
常見問題
使用動態圖像大小的UITableViewCell
UITableViewCell通過第一個單元格設置的圖像決定圖像的尺寸。如果你加載的網絡圖片和占位符圖像尺寸不一致,那么您可能會遇到奇怪的變形比例問題。下面的文章給出了解決此問題的方法:
http://www.wrichards.com/blog/2011/11/sdwebimage-fixed-width-cell-images/
處理圖像刷新
SDWebimage默認情況下做了很好的緩存處理。它忽略通過HTTP服務器返回的所有類型的緩存控制頭,並且沒有時間限制地緩存返回的圖像
它意味着你的url指向的圖片是一成不變的。更好的做法是如果url指向的圖片發生了改變,那么圖片也應該變化。
在這種情況下,你可以使用SDWebImageRefreshCached
標志。這將略微降低性能,但會尊重HTTP緩存控制頭:
[imageView sd_setImageWithURL:[NSURL URLWithString:@"https://graph.facebook.com/olivier.poitrey/picture"] placeholderImage:[UIImage imageNamed:@"avatar-placeholder.png"] options:SDWebImageRefreshCached];
添加進度指示器
參考:https://github.com/JJSaccolo/UIActivityIndicator-for-SDWebImage
安裝
有三種方法把SDWebImage安裝到您的項目中:
1)使用Cocoapods 2)復制所有文件到您的項目 3)作為靜態庫導入項目

第一步,下載SDWebImage,導入工程。github托管地址https://github.com/rs/SDWebImage
第二步,在需要的地方導入頭文件
1
#import "UIImageView+WebCache.h"
第三步,調用sd_setImageWithURL:方法緩存圖片,注意,這就是新版本的新方法,舊方法是setImageWithURL:。下面將幾個方法都介紹一下。
1. sd_setImageWithURL:
//圖片緩存的基本代碼,就是這么簡單
[self.image1 sd_setImageWithURL:imagePath1];
2. sd_setImageWithURL: completed:
//用block 可以在圖片加載完成之后做些事情
[self.image2 sd_setImageWithURL:imagePath2 completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
NSLog(@"這里可以在圖片加載完成之后做些事情");
}];
3. sd_setImageWithURL: placeholderImage:
//給一張默認圖片,先使用默認圖片,當圖片加載完成后再替換
[self.image1 sd_setImageWithURL:imagePath1 placeholderImage:[UIImage imageNamed:@"default"]];
4. sd_setImageWithURL: placeholderImage: completed:
//使用默認圖片,而且用block 在完成后做一些事情
[self.image1 sd_setImageWithURL:imagePath1 placeholderImage:[UIImage imageNamed:@"default"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
NSLog(@"圖片加載完成后做的事情");
}];
5. sd_setImageWithURL: placeholderImage: options:
//options 選擇方式
[self.image1 sd_setImageWithURL:imagePath1 placeholderImage:[UIImage imageNamed:@"default"] options:SDWebImageRetryFailed];
其他就不一一介紹了,oc是自文檔語言,看方法名就知道干什么的了。除了帶options選項的方法,其他的方法都是綜合存儲,也就是內存緩存和磁盤緩存結合的方式,如果你只需要內存緩存,那么在options這里選擇SDWebImageCacheMemoryOnly就可以了。
如果不想深入了解,到這里你已經可以用SDWebimage進行圖片緩存了,接下來我要解釋options的所有選項,以及SDWebImage內部執行流程。
一、options所有選項:
//失敗后重試
SDWebImageRetryFailed = 1 << 0,
//UI交互期間開始下載,導致延遲下載比如UIScrollView減速。
SDWebImageLowPriority = 1 << 1,
//只進行內存緩存
SDWebImageCacheMemoryOnly = 1 << 2,
//這個標志可以漸進式下載,顯示的圖像是逐步在下載
SDWebImageProgressiveDownload = 1 << 3,
//刷新緩存
SDWebImageRefreshCached = 1 << 4,
//后台下載
SDWebImageContinueInBackground = 1 << 5,
//NSMutableURLRequest.HTTPShouldHandleCookies = YES;
SDWebImageHandleCookies = 1 << 6,
//允許使用無效的SSL證書
//SDWebImageAllowInvalidSSLCertificates = 1 << 7,
//優先下載
SDWebImageHighPriority = 1 << 8,
//延遲占位符
SDWebImageDelayPlaceholder = 1 << 9,
//改變動畫形象
SDWebImageTransformAnimatedImage = 1 << 10,
二、SDWebImage內部實現過程
入口 setImageWithURL:placeholderImage:options: 會先把 placeholderImage 顯示,然后SDWebImageManager 根據 URL 開始處理圖片。
進入 SDWebImageManager-downloadWithURL:delegate:options:userInfo:,交給SDImageCache 從緩存查找圖片是否已經下載 queryDiskCacheForKey:delegate:userInfo:.
先從內存圖片緩存查找是否有圖片,如果內存中已經有圖片緩存,SDImageCacheDelegate 回調imageCache:didFindImage:forKey:userInfo: 到 SDWebImageManager。
SDWebImageManagerDelegate 回調 webImageManager:didFinishWithImage: 到UIImageView+WebCache 等前端展示圖片。
如果內存緩存中沒有,生成 NSInvocationOperation 添加到隊列開始從硬盤查找圖片是否已經緩存。
根據 URLKey 在硬盤緩存目錄下嘗試讀取圖片文件。這一步是在 NSOperation 進行的操作,所以回主線程進行結果回調 notifyDelegate:。
如果上一操作從硬盤讀取到了圖片,將圖片添加到內存緩存中(如果空閑內存過小,會先清空內存緩存)。SDImageCacheDelegate 回調 imageCache:didFindImage:forKey:userInfo:。進而回調展示圖片。
如果從硬盤緩存目錄讀取不到圖片,說明所有緩存都不存在該圖片,需要下載圖片,回調imageCache:didNotFindImageForKey:userInfo:。
共享或重新生成一個下載器 SDWebImageDownloader 開始下載圖片。
圖片下載由 NSURLConnection 來做,實現相關 delegate 來判斷圖片下載中、下載完成和下載失敗。
connection:didReceiveData: 中利用 ImageIO 做了按圖片下載進度加載效果。
connectionDidFinishLoading: 數據下載完成后交給 SDWebImageDecoder 做圖片解碼處理。
圖片解碼處理在一個 NSOperationQueue 完成,不會拖慢主線程 UI。如果有需要對下載的圖片進行二次處理,最好也在這里完成,效率會好很多。
在主線程 notifyDelegateOnMainThreadWithInfo: 宣告解碼完成,imageDecoder:didFinishDecodingImage:userInfo: 回調給 SDWebImageDownloader。
imageDownloader:didFinishWithImage: 回調給 SDWebImageManager 告知圖片下載完成。
通知所有的 downloadDelegates 下載完成,回調給需要的地方展示圖片。
將圖片保存到 SDImageCache 中,內存緩存和硬盤緩存同時保存。寫文件到硬盤也在以單獨NSInvocationOperation 完成,避免拖慢主線程。
SDImageCache 在初始化的時候會注冊一些消息通知,在內存警告或退到后台的時候清理內存圖片緩存,應用結束的時候清理過期圖片。
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, BOOLfinished, NSURL *imageURL) {
NSLog(@"下載完成");
}];
對於初級來說,用sd_setImageWithURL:的若干個方法就可以實現很好的圖片緩存。