SDWebImage內部實現過程

  • SDWebImage庫的作用:
    通過對UIImageView的類別擴展來實現異步加載替換圖片的工作。 主要用到的對象:
    • 1、UIImageView (WebCache)類別,入口封裝,實現讀取圖片完成後的回調
    • 2、SDWebImageManager,對圖片進行管理的中轉站,記錄那些圖片正在讀取。 向下層讀取Cache(調用SDImageCache),或者向網絡讀取對象(調用SDWebImageDownloader)。
      實現SDImageCache和SDWebImageDownloader的回調。
    • 3、SDImageCache,根據URL的MD5摘要對圖片進行存儲和讀取(實現存在內存中或者存在硬盤上兩種實現) 實現圖片和內存清理工作。
    • 4、SDWebImageDownloader,根據URL向網絡讀取數據(實現部分讀取和全部讀取後再通知回調兩種方式)

SDWebImage內部實現過程(新版本在各方法前加上了sd_前綴,以區分UIImageView+AFNetworking中的方法)
  • 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 可以預先下載圖片,方便後續使用。

    從上面流程可以看出,當你調用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(@"下載完成");
    }];

當服務器更新了某一張圖片資源時,客戶端需要重新加載,那麼就可以設置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,
};

SDWebImage內容補充

這裏寫圖片描述

  • SDWebImage會自動進行內存緩存和磁盤緩存

    • SDWebImage的磁盤緩存, 是按照時間來處理的, 只要緩存數據超過了最大的緩存時間, 就會自動刪除
    • SDWebImage默認的磁盤緩存時間是多久?
      • 1周
    • SDWebImage接收到內存警告會如何處理
      • 只要接收到內存警告就會調用 clearMemory 清空內存緩存
    • SDWebImage即將要被終結如何處理
      • 會調用 cleanDisk 方法, 刪除過期的文件
    • SDWebImage存儲到什麼爲止
      • caches文件夾下面
      • 新建一個default文件夾用於緩存
    • SDWebImage是如何清空緩存 ?

      • clearMemory
      • 移除NSCache中保存的所有圖片對象
    • SDWebImage是如何清除磁盤

      • cleanDisk : 清除過期的
        • 遍歷緩存目錄, 找到所有過期的文件, 並刪除
        • 查看當maxCacheSize的值, 如果刪除之後緩存的大小, 還大於maxCacheSize, 那麼就會從時間較早的開始繼續刪除, 直到緩存大小小於maxCacheSize爲止
      • clearDisk : 清除所有
        • 直接幹掉緩存文件夾
        • 重新創建一個新的文件夾, 作爲緩存文件
    • SDWebImage可以直接播放GIF圖片

      • 加載GIF圖片, 然後取出GIF圖片中所有的幀, 並且計算動畫時間
      • 根據取出的幀和動畫時間生產一張新的可動畫的圖片
    • SDWebImage它可以判斷圖片的類型

      • 圖片的十六進制數據, 的前8個字節都是一樣的, 所以可以同判斷十六進制來判斷圖片的類型
      • PNG
      • JPG

SDWebImage基本使用

  • 01 設置imageView的圖片
[cell.imageView sd_setImageWithURL:[NSURL URLWithString:app.icon] placeholderImage:[UIImage imageNamed:@"placehoder"]];
  • 02 設置圖片並計算下載進度
 //下載並設置圖片
    /*
     第一個參數:要下載圖片的url地址
     第二個參數:設置該imageView的佔位圖片
     第三個參數:傳一個枚舉值,告訴程序你下載圖片的策略是什麼
     第一個block塊:獲取當前圖片數據的下載進度
         receivedSize:已經下載完成的數據大小
         expectedSize:該文件的數據總大小
     第二個block塊:當圖片下載完成之後執行該block中的代碼
         image:下載得到的圖片數據         error:下載出現的錯誤信息
         SDImageCacheType:圖片的緩存策略(不緩存,內存緩存,沙盒緩存)
         imageURL:下載的圖片的url地址
     */
    [cell.imageView sd_setImageWithURL:[NSURL URLWithString:app.icon] placeholderImage:[UIImage imageNamed:@"placehoder"] options:SDWebImageRetryFailed progress:^(NSInteger receivedSize, NSInteger expectedSize) {

        //計算當前圖片的下載進度
        NSLog(@"%.2f",1.0 *receivedSize / expectedSize);

    } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {

    }];
  • 03 系統級內存警告如何處理(面試)
    //取消當前正在進行的所有下載操作
    [[SDWebImageManager sharedManager] cancelAll];

    //清除緩存數據(面試)
    //cleanDisk:刪除過期的文件數據,計算當前未過期的已經下載的文件數據的大小,如果發現該數據大小大於我們設置的最大緩存數據大小,那麼程序內部會按照按文件數據緩存的時間從遠到近刪除,知道小於最大緩存數據爲止。

    //clearMemory:直接刪除文件,重新創建新的文件夾
    //[[SDWebImageManager sharedManager].imageCache cleanDisk];
    [[SDWebImageManager sharedManager].imageCache clearMemory];
  • 04 SDWebImage默認的緩存時間是1周
  • 05 如何播放gif圖片
 5-1 把用戶傳入的gif圖片->NSData
 5-2 根據該Data創建一個圖片數據源(NSData->CFImageSourceRef)
 5-3 計算該數據源中一共有多少幀,把每一幀數據取出來放到圖片數組中
 5-4 根據得到的數組+計算的動畫時間-》可動畫的image
    [UIImage animatedImageWithImages:images duration:duration];
  • 06 如何判斷當前圖片類型,只判斷圖片二進制數據的第一個字節
+ (NSString *)sd_contentTypeForImageData:(NSData *)data;
  • 07 內部如何進行緩存處理?使用了NSCache類,使用和NSDictionary類似

  • 08 沙盒緩存圖片的命名方式爲對該圖片的URL進行MD5加密 echo -n "url" |MD5

  • 09 當接收到內存警告之後,內部會自動清理內存緩存

  • 10 圖片的下載順序,默認是先進先出的

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章