GitHub:SDWebImage
API documentation is available at CocoaDocs - SDWebImage
NOTE: Version 3.8 of SDWebImage requires iOS 7 or later (because of NSURLSession).

SDWebImage內(nèi)部實現(xiàn)過程(新版本在各方法前加上了sd_前綴,以區(qū)分UIImageView+AFNetworking中的方法)
圖片緩存
- UIImageView (WebCache)類別,入口封裝,實現(xiàn)讀取圖片完成后的回調(diào)
- SDWebImageManager,對圖片進行管理的中轉(zhuǎn)站,記錄那些圖片正在讀取。向下層讀取Cache(調(diào)用SDImageCache),或者向網(wǎng)絡(luò)讀取對象(調(diào)用SDWebImageDownloader)。實現(xiàn)SDImageCache和SDWebImageDownloader的回調(diào)。
- SDImageCache,根據(jù)URL的MD5摘要對圖片進行存儲和讀?。▽崿F(xiàn)存在內(nèi)存中或者存在硬盤上兩種實現(xiàn))實現(xiàn)圖片和內(nèi)存清理工作。
- SDWebImageDownloader,根據(jù)URL向網(wǎng)絡(luò)讀取數(shù)據(jù)(實現(xiàn)部分讀取和全部讀取后再通知回調(diào)兩種方式)
SDWebImage內(nèi)部實現(xiàn)過程
- 入口
setImageWithURL:placeholderImage:options:會先把 placeholderImage 顯示,然后 SDWebImageManager 根據(jù) URL 開始處理圖片。 - 進入
SDWebImageManager-downloadWithURL:delegate:options:userInfo:,交給 SDImageCache 從緩存查找圖片是否已經(jīng)下載queryDiskCacheForKey:delegate:userInfo: - 先從內(nèi)存圖片緩存查找是否有圖片,如果內(nèi)存中已經(jīng)有圖片緩存,
SDImageCacheDelegate回調(diào)imageCache:didFindImage:forKey:userInfo:到SDWebImageManager. -
SDWebImageManagerDelegate回調(diào)webImageManager:didFinishWithImage:到 UIImageView+WebCache 等前端展示圖片。 - 如果內(nèi)存緩存中沒有,生成
NSInvocationOperation添加到隊列開始從硬盤查找圖片是否已經(jīng)緩存。 - 根據(jù) URLKey 在硬盤緩存目錄下嘗試讀取圖片文件。這一步是在 NSOperation 進行的操作,所以回主線程進行結(jié)果回調(diào)
notifyDelegate:。 - 如果上一操作從硬盤讀取到了圖片,將圖片添加到內(nèi)存緩存中(如果空閑內(nèi)存過小,會先清空內(nèi)存緩存)。
SDImageCacheDelegate回調(diào)imageCache:didFindImage:forKey:userInfo:。進而回調(diào)展示圖片 - 如果從硬盤緩存目錄讀取不到圖片,說明所有緩存都不存在該圖片,需要下載圖片,回調(diào)
imageCache:didNotFindImageForKey:userInfo: - 共享或重新生成一個下載器
SDWebImageDownloader開始下載圖片。 - 圖片下載由
NSURLSession來做,實現(xiàn)相關(guān) delegate 來判斷圖片下載中、下載完成和下載失敗。 -
connection:didReceiveData:中利用 ImageIO 做了按圖片下載進度加載效果。 -
connectionDidFinishLoading:數(shù)據(jù)下載完成后交給SDWebImageDecoder做圖片解碼處理。 - 圖片解碼處理在一個 NSOperationQueue 完成,不會拖慢主線程 UI。如果有需要對下載的圖片進行二次處理,最好也在這里完成,效率會好很多。
- 在主線程
notifyDelegateOnMainThreadWithInfo:宣告解碼完成,imageDecoder:didFinishDecodingImage:userInfo:回調(diào)給 SDWebImageDownloader。 -
imageDownloader:didFinishWithImage:回調(diào)給 SDWebImageManager 告知圖片下載完成。 - 通知所有的 downloadDelegates 下載完成,回調(diào)給需要的地方展示圖片。
- 將圖片保存到 SDImageCache 中,內(nèi)存緩存和硬盤緩存同時保存。寫文件到硬盤也在以單獨 NSInvocationOperation 完成,避免拖慢主線程。
- SDImageCache 在初始化的時候會注冊一些消息通知,在內(nèi)存警告或退到后臺的時候清理內(nèi)存圖片緩存,應(yīng)用結(jié)束的時候清理過期圖片。
- SDWI 也提供了
UIButton+WebCache和MKAnnotationView+WebCache,方便使用。 - SDWebImagePrefetcher 可以預先下載圖片,方便后續(xù)使用。
從上面流程可以看出,當你調(diào)用setImageWithURL:方法的時候,他會自動去給你干這么多事,當你需要在某一具體時刻做事情的時候,你可以覆蓋這些方法。比如在下載某個圖片的過程中要響應(yīng)一個事件,就覆蓋這個方法:
覆蓋方法,指哪打哪,這個方法是下載imagePath2的時候響應(yīng)
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(@"下載完成");
}];
當服務(wù)器更新了某一張圖片資源時,客戶端需要重新加載,那么就可以設(shè)置SDWebImageOption為SDWebImageRefreshCached;附上全部的SDWebImageOptions:
typedef NS_OPTIONS(NSUInteger, SDWebImageOptions) {
/**
* By default, when a URL fail to be downloaded, the URL is blacklisted so the library won't keep trying.
* This flag disable this blacklisting.
*/
SDWebImageRetryFailed = 1 << 0,
/**
* By default, image downloads are started during UI interactions, this flags disable this feature,
* leading to delayed download on UIScrollView deceleration for instance.
*/
SDWebImageLowPriority = 1 << 1,
/**
* This flag disables on-disk caching
*/
SDWebImageCacheMemoryOnly = 1 << 2,
/**
* This flag enables progressive download, the image is displayed progressively during download as a browser would do.
* By default, the image is only displayed once completely downloaded.
*/
SDWebImageProgressiveDownload = 1 << 3,
/**
* Even if the image is cached, respect the HTTP response cache control, and refresh the image from remote location if needed.
* The disk caching will be handled by NSURLCache instead of SDWebImage leading to slight performance degradation.
* This option helps deal with images changing behind the same request URL, e.g. Facebook graph api profile pics.
* If a cached image is refreshed, the completion block is called once with the cached image and again with the final image. *
* Use this flag only if you can't make your URLs static with embeded cache busting parameter.
*/
SDWebImageRefreshCached = 1 << 4,
/**
* In iOS 4+, continue the download of the image if the app goes to background. This is achieved by asking the system for
* extra time in background to let the request finish. If the background task expires the operation will be cancelled.
*/
SDWebImageContinueInBackground = 1 << 5,
/**
* Handles cookies stored in NSHTTPCookieStore by setting * NSMutableURLRequest.HTTPShouldHandleCookies = YES; */ SDWebImageHandleCookies = 1 << 6,
/**
* Enable to allow untrusted SSL ceriticates.
* Useful for testing purposes. Use with caution in production.
*/
SDWebImageAllowInvalidSSLCertificates = 1 << 7,
/**
* By default, image are loaded in the order they were queued. This flag move them to
* the front of the queue and is loaded immediately instead of waiting for the current queue to be loaded (which * could take a while).
*/
SDWebImageHighPriority = 1 << 8,
/**
* By default, placeholder images are loaded while the image is loading. This flag will delay the loading
* of the placeholder image until after the image has finished loading.
*/
SDWebImageDelayPlaceholder = 1 << 9,
/**
* We usually don't call transformDownloadedImage delegate method on animated images,
* as most transformation code would mangle it.
* Use this flag to transform them anyway.
*/
SDWebImageTransformAnimatedImage = 1 << 10,
};
感謝:starfox寒流
獨立的異步圖像下載
downloader = [SDWebImageDownloader downloaderWithURL:url delegate:self];
這樣SDWebImageDownloaderDelegate協(xié)議的方法 imageDownloader:didFinishWithImage:被調(diào)用時下載會立即開始并完成。
獨立的異步圖像緩存
SDImageCache類提供一個創(chuàng)建空緩存的實例,并用方法imageForKey:來尋找當前緩存。
UIImage *myCachedImage = [[SDImageCache sharedImageCache] imageFromKey:myCacheKey];
存儲一個圖像到緩存是使用方法[[SDImageCache sharedImageCache] storeImage:myImage forKey:myCacheKey];
【注】默認情況下,圖像將被存儲在內(nèi)存緩存和磁盤緩存中。如果僅僅是想內(nèi)存緩存中,要使用storeImage:forKey:toDisk:方法的第三個參數(shù)帶一負值來替代。
SDWebImage庫的作用:
通過對UIImageView的類別擴展來實現(xiàn)異步加載替換圖片的工作。
主要用到的對象:
-
UIImageView (WebCache)類別,入口封裝,實現(xiàn)讀取圖片完成后的回調(diào) -
SDWebImageManager,對圖片進行管理的中轉(zhuǎn)站,記錄那些圖片正在讀取。
向下層讀取Cache(調(diào)用SDImageCache),或者向網(wǎng)絡(luò)讀取對象(調(diào)用SDWebImageDownloader)。 實現(xiàn)SDImageCache和SDWebImageDownloader的回調(diào)。 - SDImageCache,根據(jù)URL的MD5摘要對圖片進行存儲和讀?。▽崿F(xiàn)存在內(nèi)存中或者存在硬盤上兩種實現(xiàn))
實現(xiàn)圖片和內(nèi)存清理工作。 - SDWebImageDownloader,根據(jù)URL向網(wǎng)絡(luò)讀取數(shù)據(jù)(實現(xiàn)部分讀取和全部讀取后再通知回調(diào)兩種方式)
SDImageCache是怎么做數(shù)據(jù)管理的?
SDImageCache分兩個部分,一個是內(nèi)存層面的,一個是硬盤層面的。
- 內(nèi)存層面的相當是個緩存器,以Key-Value的形式存儲圖片。當內(nèi)存不夠的時候會清除所有緩存圖片。用搜索文件系統(tǒng)的方式做管理,文件替換方式是以時間為單位,剔除時間大于一周的圖片文件。
- 當
SDWebImageManager向SDImageCache要資源時,先搜索內(nèi)存層面的數(shù)據(jù),如果有直接返回,沒有的話去訪問磁盤,將圖片從磁盤讀取出來,然后做Decoder,將圖片對象放到內(nèi)存層面做備份,再返回調(diào)用層。