SDWebImage 原理及使用問題

SDWebImage託管在github上。https://github.com/rs/SDWebImage前端

這個類庫提供一個UIImageView類別以支持加載來自網絡的遠程圖片。具備緩存管理、異步下載、同一個URL下載次數控制和優化等特徵。git

SDWebImage 加載圖片的流程

  1. 入口 setImageWithURL:placeholderImage:options: 會先把 placeholderImage 顯示,而後 SDWebImageManager 根據 URL 開始處理圖片。
  2. 進入 SDWebImageManager-downloadWithURL:delegate:options:userInfo:,交給 SDImageCache 從緩存查找圖片是否已經下載 queryDiskCacheForKey:delegate:userInfo:.
  3. 先從內存圖片緩存查找是否有圖片,若是內存中已經有圖片緩存,SDImageCacheDelegate 回調 imageCache:didFindImage:forKey:userInfo: 到 SDWebImageManager。
  4. SDWebImageManagerDelegate 回調 webImageManager:didFinishWithImage: 到 UIImageView+WebCache 等前端展現圖片。
  5. 若是內存緩存中沒有,生成 NSInvocationOperation 添加到隊列開始從硬盤查找圖片是否已經緩存。
  6. 根據 URLKey 在硬盤緩存目錄下嘗試讀取圖片文件。這一步是在 NSOperation 進行的操做,因此回主線程進行結果回調 notifyDelegate:。
  7. 若是上一操做從硬盤讀取到了圖片,將圖片添加到內存緩存中(若是空閒內存太小,會先清空內存緩存)。SDImageCacheDelegate 回調 imageCache:didFindImage:forKey:userInfo:。進而回調展現圖片。
  8. 若是從硬盤緩存目錄讀取不到圖片,說明全部緩存都不存在該圖片,須要下載圖片,回調 imageCache:didNotFindImageForKey:userInfo:。
  9. 共享或從新生成一個下載器 SDWebImageDownloader 開始下載圖片。
  10. 圖片下載由 NSURLConnection 來作,實現相關 delegate 來判斷圖片下載中、下載完成和下載失敗。
  11. connection:didReceiveData: 中利用 ImageIO 作了按圖片下載進度加載效果。
  12. connectionDidFinishLoading: 數據下載完成後交給 SDWebImageDecoder 作圖片解碼處理。
  13. 圖片解碼處理在一個 NSOperationQueue 完成,不會拖慢主線程 UI。若是有須要對下載的圖片進行二次處理,最好也在這裏完成,效率會好不少。
  14. 在主線程 notifyDelegateOnMainThreadWithInfo: 宣告解碼完成,imageDecoder:didFinishDecodingImage:userInfo: 回調給 SDWebImageDownloader。
  15. imageDownloader:didFinishWithImage: 回調給 SDWebImageManager 告知圖片下載完成。
  16. 通知全部的 downloadDelegates 下載完成,回調給須要的地方展現圖片。
  17. 將圖片保存到 SDImageCache 中,內存緩存和硬盤緩存同時保存。寫文件到硬盤也在以單獨 NSInvocationOperation 完成,避免拖慢主線程。
  18. SDImageCache 在初始化的時候會註冊一些消息通知,在內存警告或退到後臺的時候清理內存圖片緩存,應用結束的時候清理過時圖片。
  19. SDWI 也提供了 UIButton+WebCache 和 MKAnnotationView+WebCache,方便使用。
  20. SDWebImagePrefetcher 能夠預先下載圖片,方便後續使用

SDWebImage庫的做用

經過對UIImageView的類別擴展來實現異步加載替換圖片的工做。github

主要用到的對象:
一、UIImageView (WebCache)類別,入口封裝,實現讀取圖片完成後的回調
二、SDWebImageManager,對圖片進行管理的中轉站,記錄那些圖片正在讀取。
向下層讀取Cache(調用SDImageCache),或者向網絡讀取對象(調用SDWebImageDownloader) 。
實現SDImageCache和SDWebImageDownloader的回調。
三、SDImageCache,根據URL的MD5摘要對圖片進行存儲和讀取(實現存在內存中或者存在硬盤上兩種實現)
實現圖片和內存清理工做。
四、SDWebImageDownloader,根據URL向網絡讀取數據(實現部分讀取和所有讀取後再通知回調兩種方式)web

其餘類:
SDWebImageDecoder,異步對圖像進行了一次解壓⋯⋯api

解惑

一、SDImageCache是怎麼作數據管理的?
SDImageCache分兩個部分,一個是內存層面的,一個是硬盤層面的。
內存層面的至關是個緩存器,以Key-Value的形式存儲圖片。當內存不夠的時候會清除全部緩存圖片。
用搜索文件系統的方式作管理,文件替換方式是以時間爲單位,剔除時間大於一週的圖片文件。
當SDWebImageManager向SDImageCache要資源時,先搜索內存層面的數據,若是有直接返回,沒有的話去訪問磁盤,將圖片從磁盤讀取出來,而後作Decoder,將圖片對象放到內存層面作備份,再返回調用層。緩存

二、爲啥必須作Decoder?
經過這個博客:http://www.cocoanetics.com/2011/10/avoiding-image-decompression-sickness/
如今明白了,因爲UIImage的imageWithData函數是每次畫圖的時候纔將Data解壓成ARGB的圖像,
因此在每次畫圖的時候,會有一個解壓操做,這樣效率很低,可是隻有瞬時的內存需求。
爲了提升效率經過SDWebImageDecoder將包裝在Data下的資源解壓,而後畫在另一張圖片上,這樣這張新圖片就再也不須要重複解壓了。服務器

這種作法是典型的空間換時間的作法。cookie

 

參考:http://blog.csdn.net/huang2009303513/article/details/41363035網絡

 三、當圖片在(內存緩存/本地disk緩存)緩存中存在的時候,url指向的後臺服務器中的圖片被換掉了,這個時候SD如何獲知圖片發生了變化,如何獲取最新的正確的圖片?app

本身在項目中遇到了這個問題,登錄事件的時候會請求主頁的頭像圖片,並進行緩存到了本地disk,可是後臺會有操做更換了頭像,若是沒有退出登錄(會清除本地disk的緩存)再次登錄,圖片就一直用的本地緩存的,只有再次登錄的時候纔會請求到新的頭像。

這個問題,SD給了這個

若是要解決這個問題,那麼在使用SD的時候用添加了一個SDWebImageReFreshCached標記的方法,相對於沒有標記的方法,這個方法會相對來講下降性能,可是能夠實時使用到最新正確的圖像。

其實現原理:

 option有11種狀況

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 embedded 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 certificates.

     * 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,

    

    /**

     * By default, image is added to the imageView after download. But in some cases, we want to

     * have the hand before setting the image (apply a filter or add it with cross-fade animation for instance)

     * Use this flag if you want to manually set the image in the completion when success

     */

    SDWebImageAvoidAutoSetImage = 1 << 11

};

相關文章
相關標籤/搜索