SDWebImage *底層探究 (一)

SDWebImage 以 category(分類)的形式,來支持圖片的異步下載與緩存。

# 其提供了以下功能:

以 UIImageView 的分類,來支持網(wǎng)絡(luò)圖片的加載與緩存管理
一個異步的圖片加載器
一個異步的內(nèi)存 + 磁盤圖片緩存
支持 GIF
支持 WebP
后臺圖片解壓縮處理
確保同一個 URL 的圖片不被多次下載
確保虛假的 URL 不會被反復(fù)加載
確保下載及緩存時,主線程不被阻塞
使用 GCD 與 ARC
支持 Arm64

UIImageView+WebCache具體實現(xiàn)如下:

/** 
* 根據(jù) url、placeholder 與 custom options 為 imageview 設(shè)置 image 
*
* 下載是異步的,并且被緩存的 
* 
* @param url 網(wǎng)絡(luò)圖片的 url 地址 
* @param placeholder 用于預(yù)顯示的圖片 
* @param options 一些定制化選項 
* @param progressBlock 下載時的 Block,其定義為:typedef void(^SDWebImageDownloaderProgressBlock)(NSInteger receivedSize, NSInteger expectedSize); 
* @param completedBlock 下載完成時的 Block,其定義為:typedef void(^SDWebImageDownloaderCompletedBlock)(UIImage *image, NSData *data, NSError *error, BOOL finished);
*/
- (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletionBlock)completedBlock { 
    #知識點: 取消加載  
    [self sd_cancelCurrentImageLoad]; 
    objc_setAssociatedObject(self, &imageURLKey, url, OBJC_ASSOCIATION_RETAIN_NONATOMIC); 
        if (!(options & SDWebImageDelayPlaceholder)) { 
             #知識點: 線程安全控制
             dispatch_main_async_safe(^{ 
                self.image = placeholder;
             }); 
        }  

        if (url) { 
            __weak __typeof(self)wself = self; 
            id <SDWebImageOperation> operation = [SDWebImageManager.sharedManager downloadImageWithURL:url options:options progress:progressBlock completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) { 
              if (!wself) return;
              dispatch_main_sync_safe(^{
                 if (!wself) return;
                 if (image && (options & SDWebImageAvoidAutoSetImage) && completedBlock) { 
                    completedBlock(image, error, cacheType, url); 
                    return; 
                 } else if (image) { 
                          wself.image = image; 
                          [wself setNeedsLayout]; 
                         }else {
                            if ((options & SDWebImageDelayPlaceholder)) {
                                 wself.image = placeholder;
                                 [wself setNeedsLayout]; 
                              }
                      }
                     if (completedBlock && finished) { 
                         completedBlock(image, error, cacheType, url); 
                    }
            });
         }];
    [self sd_setImageLoadOperation:operation forKey:@"UIImageViewImageLoad"]; 
     } else { 
        dispatch_main_async_safe(^{ 
           NSError *error = [NSError errorWithDomain:SDWebImageErrorDomain code:-1 userInfo:@{NSLocalizedDescriptionKey : @"Trying to load a nil url"}]; 
          if (completedBlock) { 
            completedBlock(nil, error, SDImageCacheTypeNone, url); 
          }
       });
   }
}```

####UIView+WebCacheOperation

  • (void)sd_cancelImageLoadOperationWithKey:(NSString *)key {
    // 取消正在進行的下載隊列
    NSMutableDictionary *operationDictionary = [self operationDictionary];
    id operations = [operationDictionary objectForKey:key];
    if (operations) {
    if ([operations isKindOfClass:[NSArray class]]) {
    for (id <SDWebImageOperation> operation in operations) {
    if (operation) {
    [operation cancel];
    }
    }
    } else if ([operations conformsToProtocol:@protocol(SDWebImageOperation)]){
    [(id<SDWebImageOperation>) operations cancel];
    }
    [operationDictionary removeObjectForKey:key];
    }
    }

框架中的所有操作實際上都是通過一個 operationDictionary(具體查看 UIView+WebCacheOperation)來管理的,而這個 Dictionary 實際上是通過動態(tài)的方式(詳情可參見:Objective-C Associated Objects 的實現(xiàn)原理)添加到 UIView 上的一個屬性,至于為什么添加到 UIView 上, 主要是因為這個 operationDictionary 需要在 UIButton 和 UIImageView 上重用,所以需要添加到它們的根類上。

當(dāng)執(zhí)行 sd_setImageWithURL:函數(shù)時,首先會 cancel 掉 operationDictionary 中已經(jīng)存在的 operation,并重新創(chuàng)建一個新的 SDWebImageCombinedOperation 對象來獲取 image,該 operation 會被存入 operationDictionary 中。

這樣來保證每個 UIImageView 對象中永遠只存在一個 operation,當(dāng)前只允許一個圖片網(wǎng)絡(luò)請求,該 operation 負(fù)責(zé)從緩存中獲取 image 或者是重新下載 image。

SDWebImageCombinedOperation的 cancel 操作同時會 cacel 掉緩存查詢的 operation 以及 downloader 的 operation

####dispatch_main_sync_safe & dispatch_main_async_safe 宏定義
再來看:
dispatch_main_async_safe(^{ 
      self.image = placeholder; 
});

上述代碼中的 dispatch_main_sync_safe與 dispatch_main_async_safe均為宏定義, 點進去一看發(fā)現(xiàn)宏是這樣定義的:

define dispatch_main_sync_safe(block)\

if ([NSThread isMainThread]) {\ 
    block();\ 
} else {\ 
    dispatch_sync(dispatch_get_main_queue(), block);\ 

}

define dispatch_main_async_safe(block)\

if ([NSThread isMainThread]) {\
     block();\ 
} else {\ 
    dispatch_async(dispatch_get_main_queue(), block);\ 
}
  • 它們的作用了: 因為圖像的繪制只能在主線程完成,所以dispatch_main_sync_safe與 dispatch_main_async_safe就是為了保證 block 能在主線程中執(zhí)行。

####SDWebImageManager
>這個類就是隱藏在 UIImageView+WebCache背后,用于處理異步下載和圖片緩存的類,當(dāng)然你也可以直接使用 SDWebImageManager 的上述方法 downloadImageWithURL:options:progress:completed:
 來直接下載圖片:

/**

  • 如果在緩存中則直接返回,否則根據(jù)所給的 URL 下載圖片
  • @param url 網(wǎng)絡(luò)圖片的 url 地址
  • @param options 一些定制化選項
  • @param progressBlock 下載時的 Block,其定義為:typedef void(^SDWebImageDownloaderProgressBlock)(NSInteger receivedSize, NSInteger expectedSize);
  • @param completedBlock 下載完成時的 Block,其定義為:typedef void(^SDWebImageDownloaderCompletedBlock)(UIImage
    *image, NSData *data, NSError *error, BOOL finished);
  • @return 返回 SDWebImageOperation 的實例
    */
  • (id <SDWebImageOperation>)downloadImageWithURL:(NSURL )url options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletionWithFinishedBlock)completedBlock {
    /
    *
    • 前面省略 n 行,主要作了如下處理:
      1. 判斷 url 的合法性
      1. 創(chuàng)建 SDWebImageCombinedOperation 對象
      1. 查看 url 是否是之前下載失敗過的
      1. 如果 url 為 nil,或者在不可重試的情況下是一個下載失敗過的 url,則直接返回操作對象并調(diào)用完成回調(diào)
        */
        // 根據(jù) URL 生成對應(yīng)的 key,沒有特殊處理為 [url absoluteString];
        NSString *key = [self cacheKeyForURL:url];
        // 去緩存中查找圖片(參見 SDImageCache)
        operation.cacheOperation = [self.imageCache queryDiskCacheForKey:key done:^(UIImage image, SDImageCacheType cacheType)
        {
        /
        ... /
        // 如果在緩存中沒有找到圖片,或者采用的 SDWebImageRefreshCached 選項,則從網(wǎng)絡(luò)下載
        if ((!image || options & SDWebImageRefreshCached) && (![self.delegate respondsToSelector:@selector(imageManager:shouldDownloadImageForURL:)] || [self.delegate imageManager:self shouldDownloadImageForURL:url])) {
        dispatch_main_sync_safe(^{
        // 如果圖片找到了,但是采用的 SDWebImageRefreshCached 選項,通知獲取到了圖片,并再次從網(wǎng)絡(luò)下載,使 NSURLCache 重新刷新
        completedBlock(image, nil, cacheType, YES, url);
        });
        }
        /
        下載選項設(shè)置 */
        // 使用 imageDownloader 開啟網(wǎng)絡(luò)下載
        id <SDWebImageOperation> subOperation = [self.imageDownloader downloadImageWithURL:url options:downloaderOptions progress:progressBlock completed:^(UIImage *downloadedImage, NSData *data, NSError error, BOOL finished) {
        /
        ... /
        if (downloadedImage && finished) {
        // 下載完成后,先將圖片保存到緩存中,然后主線程返回
        [self.imageCache storeImage:downloadedImage recalculateFromImage:NO imageData:data forKey:key toDisk:cacheOnDisk];
        }
        dispatch_main_sync_safe(^{
        if (!weakOperation.isCancelled) { completedBlock(downloadedImage, nil, SDImageCacheTypeNone, finished, url);
        }
        });
        }
        }
        /
        ... */
        } else if (image) {
        // 在緩存中找到圖片了,直接返回
        dispatch_main_sync_safe(^{
        if (!weakOperation.isCancelled) {
        completedBlock(image, nil, cacheType, YES, url);
        }
        });
        }
        }];
        return operation;}

###重點: 
>1. 在 SDWebImageManager 中管理了一個 failedURLs 的 NSMutableSet,里面下載失敗的 url 會被存儲下來。同時,可以通過 SDWebImageRetryFailed 來強制繼續(xù)重試下載

>2. 查找緩存,若緩存中沒有 image 則通過 SDWebImageDownloader 來進行下載,下載完成后通過 SDImageCache 進行緩存,會同時緩存到 memCache 和 diskCache 中

`可以看到 SDWebImageManager 這個類的主要作用就是為 UIImageView+WebCache 和 SDWebImageDownloader,SDImageCache 之間構(gòu)建一個橋梁,使它們能夠更好的協(xié)同工作,在接下來的系列文章中,就讓我們一探究竟:它是如何協(xié)調(diào)異步下載和圖片緩存的?`
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容