SDWebImage源碼解析(一)——WebCache+Manager模塊

寫(xiě)在前面

SDWebImage是一個(gè)強(qiáng)大的圖片下載庫(kù)缺菌,提供的主要功能有:圖片異步下載铛纬,圖片緩存蹬挺,圖片解碼以及其他確保程序健壯性的功能。其Github地址戳這里澈圈。

SDWebImage Class Diagram UML類(lèi)圖

SDWebImage官方提供了這個(gè)開(kāi)源庫(kù)的類(lèi)圖彬檀。

SDWebImageClassDiagram.png

為了方便閱讀在上面標(biāo)注了不同箭頭的關(guān)系∷才框架下各個(gè)模塊之間的關(guān)系都展示的很清楚了窍帝,就不再一一解釋。舉個(gè)例子拆魏,通常使用到的UIImageViewWebCache分類(lèi)下sd_setImageWithURL()方法依賴(lài)于UIViewWebCache分類(lèi)下的sd_internalSetImageWithURL()方法的實(shí)現(xiàn)盯桦。而UIViewWebCache分類(lèi)又依賴(lài)于SDWebImageManager模塊慈俯。第一篇文章則是從這個(gè)角度入手分析SDWebImage的下載流程。

SDWebImage Sequence Diagram 流程圖

官方提供的流程圖如下:

SDWebImageSequenceDiagram.png

清晰明了拥峦。


源碼分析

SDWebImageManager

SDWebImageManager是封裝好的一個(gè)單例贴膘,通過(guò)

+ (nonnull instancetype)sharedManager;


方法獲取。
SDWebImageManager是用于支撐WebCache分類(lèi)(如UIImageView+WebCache)實(shí)現(xiàn)的一個(gè)類(lèi)略号,并且連接了SDWebImageDownloader異步下載器和SDImageCache緩存模塊刑峡。
因此,在SDWebImageManager中封裝了以下幾個(gè)重要屬性:

//代理
@property (weak, nonatomic, nullable) id <SDWebImageManagerDelegate> delegate;
//緩存類(lèi)
@property (strong, nonatomic, readonly, nullable) SDImageCache *imageCache;
//異步下載器
@property (strong, nonatomic, readonly, nullable) SDWebImageDownloader *imageDownloader;

代理對(duì)象中有兩個(gè)重要方法(但是是@optional的)在下面的代碼中將會(huì)使用到:

/**
 * Controls which image should be downloaded when the image is not found in the cache.
 *
 * @param imageManager The current `SDWebImageManager`
 * @param imageURL     The url of the image to be downloaded
 *
 * @return Return NO to prevent the downloading of the image on cache misses. If not implemented, YES is implied.
 */
- (BOOL)imageManager:(nonnull SDWebImageManager *)imageManager shouldDownloadImageForURL:(nullable NSURL *)imageURL;

/**
 * Allows to transform the image immediately after it has been downloaded and just before to cache it on disk and memory.
 * NOTE: This method is called from a global queue in order to not to block the main thread.
 *
 * @param imageManager The current `SDWebImageManager`
 * @param image        The image to transform
 * @param imageURL     The url of the image to transform
 *
 * @return The transformed image object.
 */
- (nullable UIImage *)imageManager:(nonnull SDWebImageManager *)imageManager transformDownloadedImage:(nullable UIImage *)image withURL:(nullable NSURL *)imageURL;
  • 第一個(gè)方法用于詢(xún)問(wèn)代理在查找不到緩存的情況下是否需要根據(jù)url下載圖片玄柠,默認(rèn)返回YES突梦。如果返回NO,即使緩存未命中羽利,也不執(zhí)行下載操作宫患。
  • 第二個(gè)方法用于詢(xún)問(wèn)代理是否需要對(duì)下載的圖像進(jìn)行transform操作,然后緩存transform之后的圖片这弧。如果代理實(shí)現(xiàn)了這個(gè)方法娃闲,則需要返回一張圖片。

WebCache分類(lèi)中的sd_setImageWithURL最終都會(huì)調(diào)用SDWebImageManager類(lèi)中的

- (nullable id <SDWebImageOperation>)loadImageWithURL:(nullable NSURL *)url
 options:(SDWebImageOptions)options :(nullable SDWebImageDownloaderProgressBlock) progressBlock completed:(nullable SDInternalCompletionBlock)completedBlock;

進(jìn)行圖片的請(qǐng)求匾浪。
代碼注釋中有對(duì)該方法中傳入的幾個(gè)參數(shù)做出的說(shuō)明皇帮,其中需要注意傳入的SDInternalCompletionBlock 參數(shù)的作用。

/**
 * Downloads the image at the given URL if not present in cache or return the cached version otherwise.
 *
 * @param url            The URL to the image
 * @param options        A mask to specify options to use for this request
 * @param progressBlock  A block called while image is downloading
 *                       @note the progress block is executed on a background queue
 * @param completedBlock A block called when operation has been completed.
 *
 *   This parameter is required.
 * 
 *   This block has no return value and takes the requested UIImage as first parameter and the NSData representation as second parameter.
 *   In case of error the image parameter is nil and the third parameter may contain an NSError.
 *
 *   The forth parameter is an `SDImageCacheType` enum indicating if the image was retrieved from the local cache
 *   or from the memory cache or from the network.
 *
 *   The fifth parameter is set to NO when the SDWebImageProgressiveDownload option is used and the image is
 *   downloading. This block is thus called repeatedly with a partial image. When image is fully downloaded, the
 *   block is called a last time with the full image and the last parameter set to YES.
 *
 *   The last parameter is the original image URL
 *
 * @return Returns an NSObject conforming to SDWebImageOperation. Should be an instance of SDWebImageDownloaderOperation
 */

SDWebImageOptions是一個(gè)枚舉類(lèi)型蛋辈,里面存放了一些用戶(hù)可以自定義的圖片下載/緩存選項(xiàng)属拾,在代碼中有用到的話再專(zhuān)門(mén)解釋其含義。

loadImageWithURL()方法

- (nullable id <SDWebImageOperation>)loadImageWithURL:(nullable NSURL *)url
 options:(SDWebImageOptions)options :(nullable SDWebImageDownloaderProgressBlock) progressBlock completed:(nullable SDInternalCompletionBlock)completedBlock{
    // 1. 判斷傳入的url合法性
    if ([url isKindOfClass:NSString.class]) {
        url = [NSURL URLWithString:(NSString *)url];
    }

    // 將url設(shè)置為nil繼續(xù)執(zhí)行后續(xù)操作冷溶,防止程序崩潰
    if (![url isKindOfClass:NSURL.class]) {
        url = nil;
    }
    //初始化operation
    __block SDWebImageCombinedOperation *operation = [SDWebImageCombinedOperation new];
    __weak SDWebImageCombinedOperation *weakOperation = operation;

    BOOL isFailedUrl = NO;
    //2. 判斷url是否在failedURLs中
    if (url) {
        @synchronized (self.failedURLs) {// 加了同步鎖渐白,保證集合類(lèi)使用的線程安全
            isFailedUrl = [self.failedURLs containsObject:url];
        }
    }

    if (url.absoluteString.length == 0 || (!(options & SDWebImageRetryFailed) && isFailedUrl)) {
        [self callCompletionBlockForOperation:operation completion:completedBlock error:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil] url:url];
        return operation;
    }
    //將operation添加到數(shù)組中,任務(wù)完成后將被移除(后面會(huì)提到)
    @synchronized (self.runningOperations) {
        [self.runningOperations addObject:operation];
    }
    //3. 根據(jù)url獲取key
    NSString *key = [self cacheKeyForURL:url];
   //4. 請(qǐng)求緩存
    operation.cacheOperation = [self.imageCache queryCacheOperationForKey:key done:^(UIImage *cachedImage, NSData *cachedData, SDImageCacheType cacheType) {
        if (operation.isCancelled) {
            //4.1 操作已取消
            [self safelyRemoveOperationFromRunning:operation];
            return;
        }
        //需要更新已在緩存中的圖片 || 未獲取到緩存圖片
        if ((!cachedImage || options & SDWebImageRefreshCached) && (![self.delegate respondsToSelector:@selector(imageManager:shouldDownloadImageForURL:)] || [self.delegate imageManager:self shouldDownloadImageForURL:url])) {
            //4.2 options 中的 SDWebImageRefreshCached位為1 || 未獲取到緩存圖片
            //用于處理來(lái)自同一個(gè)url的圖片挂洛,但是服務(wù)器中的圖片已經(jīng)更新礼预,因此需要強(qiáng)制下載并更新緩存圖片。
            if (cachedImage && options & SDWebImageRefreshCached) {
                //緩存中已存在舊圖片虏劲,執(zhí)行回調(diào)通知托酸。
                [self callCompletionBlockForOperation:weakOperation completion:completedBlock image:cachedImage data:cachedData error:nil cacheType:cacheType finished:YES url:url];
            }
            //繼續(xù)執(zhí)行下載任務(wù)
            
            SDWebImageDownloaderOptions downloaderOptions = 0;
            //省略初始化downloaderOptions代碼
            if (cachedImage && options & SDWebImageRefreshCached) {
                //更新downloaderOptions
                // force progressive off if image already cached but forced refreshing
                downloaderOptions &= ~SDWebImageDownloaderProgressiveDownload;
                // ignore image read from NSURLCache if image if cached but force refreshing
                downloaderOptions |= SDWebImageDownloaderIgnoreCachedResponse;
            }
            //使用更新的downloaderOptions開(kāi)啟下載圖片任務(wù)
            SDWebImageDownloadToken *subOperationToken = [self.imageDownloader downloadImageWithURL:url options:downloaderOptions progress:progressBlock completed:^(UIImage *downloadedImage, NSData *downloadedData, NSError *error, BOOL finished) {
                __strong __typeof(weakOperation) strongOperation = weakOperation;
                if (!strongOperation || strongOperation.isCancelled) {
                    // 如果任務(wù)被取消,什么都不做
                } else if (error) {
                    //error handling 錯(cuò)誤處理
                    /*執(zhí)行回調(diào)將error傳出并將url放入failedURLs數(shù)組中*/
                    //代碼省略
                }
                else {
                    if ((options & SDWebImageRetryFailed)) {
                        /*options的SDWebImageRetryFailed位為1*/
                        /*默認(rèn)情況下當(dāng)url無(wú)法下載時(shí)柒巫,會(huì)添加到failedURLs數(shù)組中防止反復(fù)嘗試通過(guò)該url下載圖片励堡,而如果該位為1,則該機(jī)制失效堡掏。*/
                        @synchronized (self.failedURLs) {
                            [self.failedURLs removeObject:url];
                        }
                    }
                    //是否需要存儲(chǔ)在磁盤(pán)上                    
                    BOOL cacheOnDisk = !(options & SDWebImageCacheMemoryOnly);

                    if (options & SDWebImageRefreshCached && cachedImage && !downloadedImage) {
                        // Image refresh hit the NSURLCache cache, do not call the completion block
                        //圖片刷新命中NSURLCache的情況 && downloadedImage為空
                    } else if (downloadedImage && (!downloadedImage.images || (options & SDWebImageTransformAnimatedImage)) && [self.delegate respondsToSelector:@selector(imageManager:transformDownloadedImage:withURL:)]) {
                        //未命中NSURLCache且downloadedImage不為空
                        //options的SDWebImageTransformAnimatedImage位為1情況
                        //此時(shí)說(shuō)明圖片需要執(zhí)行transform操作
                       dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
                            //Allows to transform the image immediately after it has been downloaded and just before to cache it on disk and memory.
                           //此時(shí)調(diào)用代理方法獲取transformed image
                            UIImage *transformedImage = [self.delegate imageManager:self transformDownloadedImage:downloadedImage withURL:url];

                            if (transformedImage && finished) {
                                BOOL imageWasTransformed = ![transformedImage isEqual:downloadedImage];
                                // pass nil if the image was transformed, so we can recalculate the data from the image
                                //緩存圖片
                                [self.imageCache storeImage:transformedImage imageData:(imageWasTransformed ? nil : downloadedData) forKey:key toDisk:cacheOnDisk completion:nil];
                            }
                            //執(zhí)行回調(diào)
                            [self callCompletionBlockForOperation:strongOperation completion:completedBlock image:transformedImage data:downloadedData error:nil cacheType:SDImageCacheTypeNone finished:finished url:url];
                        });
                    } else {


                        if (downloadedImage && finished) {
                            //一般情況:即以上出現(xiàn)的options位為0且獲取到下載的圖片
                            //根據(jù)cacheOnDisk緩存downloadedImage
                            
                            [self.imageCache storeImage:downloadedImage imageData:downloadedData forKey:key toDisk:cacheOnDisk completion:nil];
                        }
                        //執(zhí)行回調(diào)
                        [self callCompletionBlockForOperation:strongOperation completion:completedBlock image:downloadedImage data:downloadedData error:nil cacheType:SDImageCacheTypeNone finished:finished url:url];
                    }
                }

                if (finished) {
                    //通過(guò)原子操作移除下載
                    [self safelyRemoveOperationFromRunning:strongOperation];
                }
            }];
            //給cancelBlock輔助应结,注意這段代碼不是在這里執(zhí)行的
            operation.cancelBlock = ^{
                [self.imageDownloader cancel:subOperationToken];
                __strong __typeof(weakOperation) strongOperation = weakOperation;
                [self safelyRemoveOperationFromRunning:strongOperation];
            };
        }else if (cachedImage) {
            //4.3 請(qǐng)求到緩存圖片 && !SDWebImageRefreshCached
            //直接回調(diào),移除操作
            __strong __typeof(weakOperation) strongOperation = weakOperation;
            [self callCompletionBlockForOperation:strongOperation completion:completedBlock image:cachedImage data:cachedData error:nil cacheType:cacheType finished:YES url:url];
            [self safelyRemoveOperationFromRunning:operation];
        } else {
            // 4.4 圖片沒(méi)有在緩存中 && 代理沒(méi)有允許下載操作
            __strong __typeof(weakOperation) strongOperation = weakOperation;
            [self callCompletionBlockForOperation:strongOperation completion:completedBlock image:nil data:nil error:nil cacheType:SDImageCacheTypeNone finished:YES url:url];
            [self safelyRemoveOperationFromRunning:operation];
        }
    }];

    return operation;
}

方法內(nèi)部的注釋詳細(xì)描述了SDWebImageManager的loadImageWithURL工作流程。概括起來(lái)其實(shí)很簡(jiǎn)單:首先判斷緩存中是否能獲取到圖片鹅龄,如果沒(méi)獲取到則使用異步下載器下載揩慕,然后使用緩存類(lèi)緩存,執(zhí)行回調(diào)返回圖片扮休。如果緩存中能夠獲取到迎卤,執(zhí)行回調(diào)返回緩存中的圖片。

下一篇文章將著重分析SDWebImage的緩存實(shí)現(xiàn)玷坠。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末蜗搔,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子八堡,更是在濱河造成了極大的恐慌樟凄,老刑警劉巖,帶你破解...
    沈念sama閱讀 216,591評(píng)論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件兄渺,死亡現(xiàn)場(chǎng)離奇詭異缝龄,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)溶耘,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,448評(píng)論 3 392
  • 文/潘曉璐 我一進(jìn)店門(mén)二拐,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人凳兵,你說(shuō)我怎么就攤上這事∑笕恚” “怎么了庐扫?”我有些...
    開(kāi)封第一講書(shū)人閱讀 162,823評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)仗哨。 經(jīng)常有香客問(wèn)我形庭,道長(zhǎng),這世上最難降的妖魔是什么厌漂? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,204評(píng)論 1 292
  • 正文 為了忘掉前任萨醒,我火速辦了婚禮,結(jié)果婚禮上苇倡,老公的妹妹穿的比我還像新娘富纸。我一直安慰自己,他們只是感情好旨椒,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,228評(píng)論 6 388
  • 文/花漫 我一把揭開(kāi)白布晓褪。 她就那樣靜靜地躺著,像睡著了一般综慎。 火紅的嫁衣襯著肌膚如雪涣仿。 梳的紋絲不亂的頭發(fā)上,一...
    開(kāi)封第一講書(shū)人閱讀 51,190評(píng)論 1 299
  • 那天,我揣著相機(jī)與錄音好港,去河邊找鬼愉镰。 笑死,一個(gè)胖子當(dāng)著我的面吹牛钧汹,可吹牛的內(nèi)容都是我干的岛杀。 我是一名探鬼主播,決...
    沈念sama閱讀 40,078評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼崭孤,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼类嗤!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起辨宠,我...
    開(kāi)封第一講書(shū)人閱讀 38,923評(píng)論 0 274
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤遗锣,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后嗤形,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體精偿,經(jīng)...
    沈念sama閱讀 45,334評(píng)論 1 310
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,550評(píng)論 2 333
  • 正文 我和宋清朗相戀三年赋兵,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了笔咽。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,727評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡霹期,死狀恐怖叶组,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情历造,我是刑警寧澤甩十,帶...
    沈念sama閱讀 35,428評(píng)論 5 343
  • 正文 年R本政府宣布,位于F島的核電站吭产,受9級(jí)特大地震影響侣监,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜臣淤,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,022評(píng)論 3 326
  • 文/蒙蒙 一橄霉、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧邑蒋,春花似錦姓蜂、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,672評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至遮咖,卻和暖如春滩字,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 32,826評(píng)論 1 269
  • 我被黑心中介騙來(lái)泰國(guó)打工麦箍, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留漓藕,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 47,734評(píng)論 2 368
  • 正文 我出身青樓挟裂,卻偏偏與公主長(zhǎng)得像享钞,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子诀蓉,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,619評(píng)論 2 354

推薦閱讀更多精彩內(nèi)容