SDWebImage源碼解析(三)

1 概述

這篇博文中,我將分析SDWebImageManagerSDImageCacheSDWebImageManager擁有一個SDWebImageCacheSDWebImageDownloader屬性分別用於圖片的緩存和加載處理。爲UIView及其子類提供了加載圖片的統一接口。管理正在加載操做的集合,這個類是一個單列。同時管理各類加載選項的處理。SDImageCache負責SDWebImage的整個緩存工做,是一個單列對象。緩存路徑處理、緩存名字處理、管理內存緩存和磁盤緩存的建立和刪除、根據指定key獲取圖片、存入圖片的類型處理、根據緩存的建立和修改日期刪除緩存。html

2 SDWebImageManager分析

UIImageView等各類視圖經過UIView+WebCache分類的sd_internalSetImageWithURL方法來調用SDWebImageManager類的以下方法實現圖片加載:git

/**
 這個方法是核心方法。UIImageView等這種分類都默認經過調用這個方法來獲取數據。

 @param url 圖片的url地址
 @param options 獲取圖片的屬性
 @param progressBlock 加載進度回調
 @param completedBlock 加載完成回調
 @return 返回一個加載的載體對象。以便提供給後面取消刪除等。
 */
- (nullable id <SDWebImageOperation>)loadImageWithURL:(nullable NSURL *)url
                                              options:(SDWebImageOptions)options
                                             progress:(nullable SDWebImageDownloaderProgressBlock)progressBlock
                                            completed:(nullable SDInternalCompletionBlock)completedBlock;

首先看他地第二個參數options。這個參數指定了圖片加載過程當中的不一樣選項。指定不一樣選項,SDWebImage能夠根據選項作不一樣的處理,這是一個枚舉類型,多個選項之間能夠組合使用。github

/**
 枚舉,定義了圖片加載處理過程當中的選項
 */
typedef NS_OPTIONS(NSUInteger, SDWebImageOptions) {
    /*
     默認狀況下,當一個URL下載失敗的時候,這個URL會被加入黑名單列表,下次再有這個url的請求則中止請求。
     若是爲true,這個值表示須要再嘗試請求。
     */
    SDWebImageRetryFailed = 1 << 0,

    /*
     默認狀況下,當UI能夠交互的時候就開始加載圖片。這個標記能夠阻止這個時候加載。
     而是當UIScrollView開始減速滑動的時候開始加載。
     */
    SDWebImageLowPriority = 1 << 1,

    /*
     這個屬性禁止磁盤緩存
     */
    SDWebImageCacheMemoryOnly = 1 << 2,

    /*
     這個標記容許圖片在加載過程當中顯示,就像瀏覽器那樣。
     默認狀況下,圖片只會在加載完成之後再顯示。
     */
    SDWebImageProgressiveDownload = 1 << 3,

    /*
     *即便本地已經緩存了圖片,可是根據HTTP的緩存策略去網絡上加載圖片。也就是說本地緩存了也無論了,嘗試從網絡上加載數據。可是具體是從代理加載、HTTP緩存加載、仍是原始服務器加載這個就更具HTTP的請求頭配置。
     *使用NSURLCache而不是SDWebImage來處理磁盤緩存。從而可能會致使輕微的性能損害。
     *這個選項專門用於處理,url地址沒有變,可是url對於的圖片數據在服務器改變的狀況。
     *若是一個緩存圖片更新了,則completion這個回調會被調用兩次,一次返回緩存圖片,一次返回最終圖片。
     *咱們只有在不能確保URL和他對應的內容不能徹底對應的時候才使用這個標記。
     */
    SDWebImageRefreshCached = 1 << 4,

    /*
     當應用進入後臺之後,圖片繼續下載。應用進入後臺之後,經過向系統申請額外的時間來完成。若是時間超時,那麼下載操做會被取消。
     */
    SDWebImageContinueInBackground = 1 << 5,

    /*
     處理緩存在`NSHTTPCookieStore`對象裏面的cookie。經過設置`NSMutableURLRequest.HTTPShouldHandleCookies = YES`來實現的。
     */
    SDWebImageHandleCookies = 1 << 6,

    /*
     *容許非信任的SSL證書請求。
     *在測試的時候頗有用。可是正式環境要當心使用。
     */
    SDWebImageAllowInvalidSSLCertificates = 1 << 7,

    /*
     * 默認狀況下,圖片加載的順序是根據加入隊列的順序加載的。可是這個標記會把任務加入隊列的最前面。
     */
    SDWebImageHighPriority = 1 << 8,
    
    /*
     默認狀況下,在圖片加載的過程當中,會顯示佔位圖。
     可是這個標記會阻止顯示佔位圖直到圖片加載完成。
     */
    SDWebImageDelayPlaceholder = 1 << 9,

    /*
     *默認狀況下,咱們不會去調用`animated images`(估計就是多張圖片循環顯示或者GIF圖片)的`transformDownloadedImage`代理方法來處理圖片。由於大部分transformation操做會對圖片作無用處理。
     *用這個標記表示不管如何都要對圖片作transform處理。
     */
    SDWebImageTransformAnimatedImage = 1 << 10,
    
    /*
     *默認狀況下,圖片再下載完成之後都會被自動加載到UIImageView對象上面。可是有時咱們但願UIImageView加載咱們手動處理之後的圖片。
     *這個標記容許咱們在completion這個Block中手動設置處理好之後的圖片。
     */
    SDWebImageAvoidAutoSetImage = 1 << 11,
    
    /*
     *默認狀況下,圖片會按照他的原始大小來解碼顯示。根據設備的內存限制,這個屬性會調整圖片的尺寸到合適的大小再解壓縮。
     *若是`SDWebImageProgressiveDownload`標記被設置了,則這個flag不起做用。
     */
    SDWebImageScaleDownLargeImages = 1 << 12
};

接下來我先看SDWebImageManager的初始化過程。數組

- (nonnull instancetype)init {
    SDImageCache *cache = [SDImageCache sharedImageCache];
    SDWebImageDownloader *downloader = [SDWebImageDownloader sharedDownloader];
    return [self initWithCache:cache downloader:downloader];
}

/**
 初始化SDImageCache和SDWebImageDownloader對象

 @param cache SDImageCache對象
 @param downloader SDWebImageDownloader對象
 @return 返回初始化結果
 */
- (nonnull instancetype)initWithCache:(nonnull SDImageCache *)cache downloader:(nonnull SDWebImageDownloader *)downloader {
    if ((self = [super init])) {
        _imageCache = cache;
        _imageDownloader = downloader;
        //用於保存加載失敗的url集合
        _failedURLs = [NSMutableSet new];
        //用於保存當前正在加載的Operation
        _runningOperations = [NSMutableArray new];
    }
    return self;
}

loadImageWithURL方法是SDWebImageManager最核心的方法,實現過程:瀏覽器

/**
 這個方法是核心方法。UIImageView等這種分類都默認經過調用這個方法來獲取數據。

 @param url 圖片的url地址
 @param options 獲取圖片的屬性
 @param progressBlock 加載進度回調
 @param completedBlock 加載完成回調
 @return 返回一個加載的載體對象。以便提供給後面取消刪除等。
 */
- (id <SDWebImageOperation>)loadImageWithURL:(nullable NSURL *)url
                                     options:(SDWebImageOptions)options
                                    progress:(nullable SDWebImageDownloaderProgressBlock)progressBlock
                                   completed:(nullable SDInternalCompletionBlock)completedBlock {
    /*
     若是傳入的url是NSString格式的。則轉換爲NSURL類型再處理
     */
    if ([url isKindOfClass:NSString.class]) {
        url = [NSURL URLWithString:(NSString *)url];
    }

    // Prevents app crashing on argument type error like sending NSNull instead of NSURL
    //若是url不會NSURL類型的對象。則置爲nil
    if (![url isKindOfClass:NSURL.class]) {
        url = nil;
    }
    /*
     圖片加載獲取獲取過程當中綁定一個`SDWebImageCombinedOperation`對象。以方便後續再經過這個對象對url的加載控制。
     */
    __block SDWebImageCombinedOperation *operation = [SDWebImageCombinedOperation new];
    __weak SDWebImageCombinedOperation *weakOperation = operation;

    BOOL isFailedUrl = NO;
    //當前url是否在失敗url的集合裏面
    if (url) {
        @synchronized (self.failedURLs) {
            isFailedUrl = [self.failedURLs containsObject:url];
        }
    }
    /*
     若是url是失敗的url或者url有問題等各類問題。則直接根據opeation來作異常狀況的處理
     */
    if (url.absoluteString.length == 0 || (!(options & SDWebImageRetryFailed) && isFailedUrl)) {
        //構建回調Block
        [self callCompletionBlockForOperation:operation completion:completedBlock error:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil] url:url];
        return operation;
    }
    //把加載圖片的一個載體存入runningOperations。裏面是全部正在作圖片加載過程的operation的集合。
    @synchronized (self.runningOperations) {
        [self.runningOperations addObject:operation];
    }
    //根據url獲取url對應的key
    NSString *key = [self cacheKeyForURL:url];
    /*
    *若是圖片是從內存加載,則返回的cacheOperation是nil,
    *若是是從磁盤加載,則返回的cacheOperation是`NSOperation`對象。
    *若是是從網絡加載,則返回的cacheOperation對象是`SDWebImageDownloaderOperation`對象。
    */
    operation.cacheOperation = [self.imageCache queryCacheOperationForKey:key done:^(UIImage *cachedImage, NSData *cachedData, SDImageCacheType cacheType) {
        //從緩存中獲取圖片數據返回
        //若是已經取消了操做。則直接返回而且移除對應的opetation對象
        if (operation.isCancelled) {
            [self safelyRemoveOperationFromRunning:operation];
            return;
        }
        
        if ((!cachedImage || options & SDWebImageRefreshCached) && (![self.delegate respondsToSelector:@selector(imageManager:shouldDownloadImageForURL:)] || [self.delegate imageManager:self shouldDownloadImageForURL:url])) {
            /**
             若是從緩存獲取圖片失敗。或者設置了SDWebImageRefreshCached來忽略緩存。則先把緩存的圖片返回。
             */
            if (cachedImage && options & SDWebImageRefreshCached) {
                //構建回調Block
                [self callCompletionBlockForOperation:weakOperation completion:completedBlock image:cachedImage data:cachedData error:nil cacheType:cacheType finished:YES url:url];
            }

            // download if no image or requested to refresh anyway, and download allowed by delegate
            /*
             把圖片加載的`SDWebImageOptions`類型枚舉轉換爲圖片下載的`SDWebImageDownloaderOptions`類型的枚舉
             */
            SDWebImageDownloaderOptions downloaderOptions = 0;
            if (options & SDWebImageLowPriority) downloaderOptions |= SDWebImageDownloaderLowPriority;
            if (options & SDWebImageProgressiveDownload) downloaderOptions |= SDWebImageDownloaderProgressiveDownload;
            if (options & SDWebImageRefreshCached) downloaderOptions |= SDWebImageDownloaderUseNSURLCache;
            if (options & SDWebImageContinueInBackground) downloaderOptions |= SDWebImageDownloaderContinueInBackground;
            if (options & SDWebImageHandleCookies) downloaderOptions |= SDWebImageDownloaderHandleCookies;
            if (options & SDWebImageAllowInvalidSSLCertificates) downloaderOptions |= SDWebImageDownloaderAllowInvalidSSLCertificates;
            if (options & SDWebImageHighPriority) downloaderOptions |= SDWebImageDownloaderHighPriority;
            if (options & SDWebImageScaleDownLargeImages) downloaderOptions |= SDWebImageDownloaderScaleDownLargeImages;
            /*
             若是設置了強制刷新緩存的選項。則`SDWebImageDownloaderProgressiveDownload`選項失效而且添加`SDWebImageDownloaderIgnoreCachedResponse`選項。
             */
            if (cachedImage && options & SDWebImageRefreshCached) {
                // 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;
            }
            /*
             新建一個網絡下載的操做。
             */
            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) {
                   //若是operation已經被取消了,則什麼也不作
                } else if (error) {
                    //若是加載出錯。則直接返回回調。而且添加到failedURLs中
                    [self callCompletionBlockForOperation:strongOperation completion:completedBlock error:error url:url];

                    if (   error.code != NSURLErrorNotConnectedToInternet
                        && error.code != NSURLErrorCancelled
                        && error.code != NSURLErrorTimedOut
                        && error.code != NSURLErrorInternationalRoamingOff
                        && error.code != NSURLErrorDataNotAllowed
                        && error.code != NSURLErrorCannotFindHost
                        && error.code != NSURLErrorCannotConnectToHost
                        && error.code != NSURLErrorNetworkConnectionLost) {
                        @synchronized (self.failedURLs) {
                            [self.failedURLs addObject:url];
                        }
                    }
                }
                else {
                    //網絡圖片加載成功
                    if ((options & SDWebImageRetryFailed)) {
                        //若是有重試失敗下載的選項。則把url從failedURLS中移除
                        @synchronized (self.failedURLs) {
                            [self.failedURLs removeObject:url];
                        }
                    }
                    
                    BOOL cacheOnDisk = !(options & SDWebImageCacheMemoryOnly);

                    if (options & SDWebImageRefreshCached && cachedImage && !downloadedImage) {
                        // Image refresh hit the NSURLCache cache, do not call the completion block
                        //若是成功下載圖片。而且圖片是動態圖片。而且設置了SDWebImageTransformAnimatedImage屬性。則處理圖片
                    } else if (downloadedImage && (!downloadedImage.images || (options & SDWebImageTransformAnimatedImage)) && [self.delegate respondsToSelector:@selector(imageManager:transformDownloadedImage:withURL:)]) {
                        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
                            //獲取transform之後的圖片
                            UIImage *transformedImage = [self.delegate imageManager:self transformDownloadedImage:downloadedImage withURL:url];
                            //存儲transform之後的的圖片
                            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];
                            }
                            //回調拼接
                            [self callCompletionBlockForOperation:strongOperation completion:completedBlock image:transformedImage data:downloadedData error:nil cacheType:SDImageCacheTypeNone finished:finished url:url];
                        });
                    } else {
                        //若是成功下載圖片。而且圖片不是圖片。則直接緩存和回調
                        if (downloadedImage && finished) {
                            [self.imageCache storeImage:downloadedImage imageData:downloadedData forKey:key toDisk:cacheOnDisk completion:nil];
                        }
                        //回調拼接
                        [self callCompletionBlockForOperation:strongOperation completion:completedBlock image:downloadedImage data:downloadedData error:nil cacheType:SDImageCacheTypeNone finished:finished url:url];
                    }
                }
                //從正在加載的圖片操做集合中移除當前操做
                if (finished) {
                    [self safelyRemoveOperationFromRunning:strongOperation];
                }
            }];
            //重置cancelBlock,取消下載operation
            operation.cancelBlock = ^{
                [self.imageDownloader cancel:subOperationToken];
                __strong __typeof(weakOperation) strongOperation = weakOperation;
                [self safelyRemoveOperationFromRunning:strongOperation];
            };
        } else if (cachedImage) {
            //若是獲取到了緩存圖片。在直接經過緩存圖片處理
            __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 {
            // Image not in cache and download disallowed by delegate
            //圖片麼有緩存、而且圖片也沒有下載
            __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;
}

經過對這個方法的分析,他主要實現的功能有:緩存

  • 建立一個SDWebImageCombinedOperation對象,調用者能夠經過這個對象來對加載作取消等操做。這個對象的cancelOperation屬性有以下幾種狀況。服務器

    • 若是圖片是從內存加載,則返回的cacheOperation是nil。cookie

    • 若是是從磁盤加載,則返回的cacheOperation是NSOperation對象。網絡

    • 若是是從網絡加載,則返回的cacheOperation對象是SDWebImageDownloaderOperation對象。app

  • 經過failedURLs屬性來保存加載失敗的url。經過它能夠阻止失敗的url再次加載,提升用戶體驗。

  • 經過runningOperations屬性記錄當前正在加載的Operation列表。

  • 加載結束之後,經過callCompletionBlockForOperation方法來拼接回調Block。

  • SDWebImageOptions類型的枚舉值轉換爲SDWebImageDownloaderOptions類型的枚舉值。

  • 圖片成功從網絡加載之後,經過imageCache屬性的storeImage方法來緩存圖片。

另外還有一些輔助性的方法,用於處理緩存判斷、url與key轉換等功能:

/**
 根據url獲取url對應的緩存key。
 若是有實現指定的url轉換key的Block,則用這個方式轉換爲key。
 不然直接用url的絕對值多爲key

 @param url url
 @return 緩存的key
 */
- (nullable NSString *)cacheKeyForURL:(nullable NSURL *)url {
    if (!url) {
        return @"";
    }
    if (self.cacheKeyFilter) {
        return self.cacheKeyFilter(url);
    } else {
        return url.absoluteString;
    }
}

/**
 一個url的緩存是否存在

 @param url 緩存數據對應的url
 @param completionBlock 緩存結果回調
 */
- (void)cachedImageExistsForURL:(nullable NSURL *)url
                     completion:(nullable SDWebImageCheckCacheCompletionBlock)completionBlock {
    NSString *key = [self cacheKeyForURL:url];
    //內存裏面是否有key的緩存
    BOOL isInMemoryCache = ([self.imageCache imageFromMemoryCacheForKey:key] != nil);
    //內存緩存
    if (isInMemoryCache) {
        // making sure we call the completion block on the main queue
        dispatch_async(dispatch_get_main_queue(), ^{
            if (completionBlock) {
                completionBlock(YES);
            }
        });
        return;
    }
    //磁盤緩存
    [self.imageCache diskImageExistsWithKey:key completion:^(BOOL isInDiskCache) {
        // the completion block of checkDiskCacheForImageWithKey:completion: is always called on the main queue, no need to further dispatch
        if (completionBlock) {
            completionBlock(isInDiskCache);
        }
    }];
}

/**
 url是否有磁盤緩存數據

 @param url url
 @param completionBlock 回調
 */
- (void)diskImageExistsForURL:(nullable NSURL *)url
                   completion:(nullable SDWebImageCheckCacheCompletionBlock)completionBlock {
    NSString *key = [self cacheKeyForURL:url];
    
    [self.imageCache diskImageExistsWithKey:key completion:^(BOOL isInDiskCache) {
        // the completion block of checkDiskCacheForImageWithKey:completion: is always called on the main queue, no need to further dispatch
        if (completionBlock) {
            completionBlock(isInDiskCache);
        }
    }];
}

2.1 SDWebImageCombinedOperation分析

從上面的方法,發現loadImageWithURL方法會返回一個SDWebImageCombinedOperation給調用者,這個對象有個cancel方法,這個方法繼承自SDWebImageOperation協議。方法裏面會調用SDWebImageDownlaoderOperation或者NSOperation的cancel方法

/**
 經過這個對象關聯一個`SDWebImageDownloaderOperation`對象
 */
@interface SDWebImageCombinedOperation : NSObject <SDWebImageOperation>

/**
 用於判斷Operation是否已經取消
 */
@property (assign, nonatomic, getter = isCancelled) BOOL cancelled;

/**
 取消回調
 */
@property (copy, nonatomic, nullable) SDWebImageNoParamsBlock cancelBlock;

/**
 SDWebImageDownloaderOperation對象。能夠經過這個屬性取消一個NSOperation
 */
@property (strong, nonatomic, nullable) NSOperation *cacheOperation;

@end

@implementation SDWebImageCombinedOperation

/**
 取消Operation的回調Block

 @param cancelBlock 回調Block
 */
- (void)setCancelBlock:(nullable SDWebImageNoParamsBlock)cancelBlock {
    // check if the operation is already cancelled, then we just call the cancelBlock
    if (self.isCancelled) {
        if (cancelBlock) {
            cancelBlock();
        }
        _cancelBlock = nil; // don't forget to nil the cancelBlock, otherwise we will get crashes
    } else {
        _cancelBlock = [cancelBlock copy];
    }
}

/**
 調用cancel方法。這個方法繼承自`SDWebImageOperation`協議。方法裏面會調用`SDWebImageDownlaoderOperation`或者`NSOperation`的cancel方法
 */
- (void)cancel {
    self.cancelled = YES;
    if (self.cacheOperation) {
        //調用`SDWebImageDownlaoderOperation`或者`NSOperation`的cancel方法
        [self.cacheOperation cancel];
        self.cacheOperation = nil;
    }
    if (self.cancelBlock) {
        self.cancelBlock();
        
        // TODO: this is a temporary fix to #809.
        // Until we can figure the exact cause of the crash, going with the ivar instead of the setter
        //        self.cancelBlock = nil;
        _cancelBlock = nil;
    }
}

@end

那麼取消一個Operation是在哪裏呢?其實就在UIView+WebCache中,全部使用SDWebImage的View均可以使用這個方法來取消下載Operation:

/**
 取消當前Class對應的全部加載請求
 */
- (void)sd_cancelCurrentImageLoad {
    [self sd_cancelImageLoadOperationWithKey:NSStringFromClass([self class])];
}

上面這個方法又會調用UIView+WebCacheOperation分類的sd_cancelImageLoadOperationWithKey方法來實現,這個方法會調用SDWebImageCombinedOperation對象的cancel方法,而後在cancel方法中再調用SDWebImageDownloadOperation或者NSOperationcancel方法:

/**
 取消當前key對應的全部`SDWebImageCombinedOperation`對象

 @param key Operation對應的key
 */
- (void)sd_cancelImageLoadOperationWithKey:(nullable NSString *)key {
    // Cancel in progress downloader from queue
    //獲取當前View對應的全部key
    SDOperationsDictionary *operationDictionary = [self operationDictionary];
    //獲取對應的圖片加載Operation
    id operations = operationDictionary[key];
    //取消全部當前View對應的全部Operation
    if (operations) {
        if ([operations isKindOfClass:[NSArray class]]) {
            for (id <SDWebImageOperation> operation in operations) {
                if (operation) {
                    //SDWebImageCombinedOperation對象的cancel方法
                    [operation cancel];
                }
            }
        } else if ([operations conformsToProtocol:@protocol(SDWebImageOperation)]){
            [(id<SDWebImageOperation>) operations cancel];
        }
        [operationDictionary removeObjectForKey:key];
    }
}

3 SDImageCache分析

從上面的代碼中,發現SDWebImageManager經過SDImageCache來獲取/存儲圖片,並且SDImageCache是一個單列對象。他的具體實現能夠總結爲以下幾點:

  • 經過AutoPurgeCache這個NSCache子類來管理內存緩存。當接收到內存警告的時候,移除內存緩存的全部對象。

  • 接收到UIApplicationDidReceiveMemoryWarningNotification通知之後,會刪除內存中緩存的圖片。

  • 接收到UIApplicationWillTerminateNotification通知之後,會經過deleteOldFiles方法刪除老的圖片。具體刪除規則以下:

    • 緩存大小、過時日期、是否解壓縮緩存、是否容許內存緩存都是經過SDImageCacheConfig這個對象來配置的。

    • 首先會迭代緩存目錄下的全部文件,對於大於一週的圖片數據所有刪除。

    • 而後會記錄緩存目錄的全部大小,若是當前緩存大於默認緩存,則按照建立日期開始刪除圖片緩存,直到緩存大小小於默認緩存大小。

  • 當接收到UIApplicationDidEnterBackgroundNotification通知之後,會調用deleteOldFilesWithCompletionBlock來清理緩存數據。

  • 定義了一些列方法來處理圖片的獲取、緩存、移除操做。主要有下面幾個方法:

    • queryCacheOperationForKey查詢指定key對應的緩存圖片,先從內存查找,而後從磁盤查找。

    • removeImageForKey移除指定的緩存圖片。

    • diskImageDataBySearchingAllPathsForKey在磁盤上查找指定key對應的圖片。

    • storeImageDataToDisk把指定的圖片數據存入磁盤。

  • 經過cachedFileNameForKey方法獲取一張圖片對應的MD5加密的緩存名字。

SDImageCache的完整實現以下:

@interface AutoPurgeCache : NSCache
@end

/**
 若是接收到內存警告、移除全部的緩存對象
 */
@implementation AutoPurgeCache

- (nonnull instancetype)init {
    self = [super init];
    if (self) {
#if SD_UIKIT
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(removeAllObjects) name:UIApplicationDidReceiveMemoryWarningNotification object:nil];
#endif
    }
    return self;
}

- (void)dealloc {
#if SD_UIKIT
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidReceiveMemoryWarningNotification object:nil];
#endif
}

@end
/**
 計算一張圖片佔用內存的大小

 @param image 圖片
 @return 佔用內存大小
 */
FOUNDATION_STATIC_INLINE NSUInteger SDCacheCostForImage(UIImage *image) {
#if SD_MAC
    return image.size.height * image.size.width;
#elif SD_UIKIT || SD_WATCH
    return image.size.height * image.size.width * image.scale * image.scale;
#endif
}
/**
 單列對象、用處管理圖片的緩存以及緩存圖片的處理
 */
@interface SDImageCache ()

#pragma mark - Properties
@property (strong, nonatomic, nonnull) NSCache *memCache;
@property (strong, nonatomic, nonnull) NSString *diskCachePath;
@property (strong, nonatomic, nullable) NSMutableArray<NSString *> *customPaths;
@property (SDDispatchQueueSetterSementics, nonatomic, nullable) dispatch_queue_t ioQueue;

@end

@implementation SDImageCache {
    NSFileManager *_fileManager;
}
#pragma mark - Singleton, init, dealloc
+ (nonnull instancetype)sharedImageCache {
    static dispatch_once_t once;
    static id instance;
    dispatch_once(&once, ^{
        instance = [self new];
    });
    return instance;
}

- (instancetype)init {
    return [self initWithNamespace:@"default"];
}

- (nonnull instancetype)initWithNamespace:(nonnull NSString *)ns {
    NSString *path = [self makeDiskCachePath:ns];
    return [self initWithNamespace:ns diskCacheDirectory:path];
}

- (nonnull instancetype)initWithNamespace:(nonnull NSString *)ns
                       diskCacheDirectory:(nonnull NSString *)directory {
    if ((self = [super init])) {
        NSString *fullNamespace = [@"com.hackemist.SDWebImageCache." stringByAppendingString:ns];
        // 初始化一個串行的dispatch_queue_t
        _ioQueue = dispatch_queue_create("com.hackemist.SDWebImageCache", DISPATCH_QUEUE_SERIAL);
        //初始化緩存策略配置對象
        _config = [[SDImageCacheConfig alloc] init];
        
        // 初始化內存緩存對象
        _memCache = [[AutoPurgeCache alloc] init];
        _memCache.name = fullNamespace;

        // 初始化磁盤緩存路徑
        if (directory != nil) {
            _diskCachePath = [directory stringByAppendingPathComponent:fullNamespace];
        } else {
            NSString *path = [self makeDiskCachePath:ns];
            _diskCachePath = path;
        }

        dispatch_sync(_ioQueue, ^{
            _fileManager = [NSFileManager new];
        });

#if SD_UIKIT
        /*
         當應用收到內存警告的時候,清除內存緩存。
         */
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(clearMemory)
                                                     name:UIApplicationDidReceiveMemoryWarningNotification
                                                   object:nil];
        /*
         當應用終止的時候,清除老數據
         */
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(deleteOldFiles)
                                                     name:UIApplicationWillTerminateNotification
                                                   object:nil];
        /*
         當應用進入後臺的時候,在後臺刪除老數據
         */
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(backgroundDeleteOldFiles)
                                                     name:UIApplicationDidEnterBackgroundNotification
                                                   object:nil];
#endif
    }

    return self;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    SDDispatchQueueRelease(_ioQueue);
}

/**
 當前queue是否在ioQueue
 */
- (void)checkIfQueueIsIOQueue {
    const char *currentQueueLabel = dispatch_queue_get_label(DISPATCH_CURRENT_QUEUE_LABEL);
    const char *ioQueueLabel = dispatch_queue_get_label(self.ioQueue);
    if (strcmp(currentQueueLabel, ioQueueLabel) != 0) {
        NSLog(@"This method should be called from the ioQueue");
    }
}

#pragma mark - Cache paths
/*
 添加只能讀的緩存目錄
 */
- (void)addReadOnlyCachePath:(nonnull NSString *)path {
    if (!self.customPaths) {
        self.customPaths = [NSMutableArray new];
    }

    if (![self.customPaths containsObject:path]) {
        [self.customPaths addObject:path];
    }
}

/**
 獲取指定key對應的完整緩存路徑

 @param key key,對應一張圖片。好比圖片的名字
 @param path 指定根目錄
 @return 完整目錄
 */
- (nullable NSString *)cachePathForKey:(nullable NSString *)key inPath:(nonnull NSString *)path {
    NSString *filename = [self cachedFileNameForKey:key];
    return [path stringByAppendingPathComponent:filename];
}

- (nullable NSString *)defaultCachePathForKey:(nullable NSString *)key {
    return [self cachePathForKey:key inPath:self.diskCachePath];
}


/**
 MD5加密
 X 表示以十六進制形式輸出
 02 表示不足兩位,前面補0輸出;出過兩位,不影響

 @param key key
 @return 加密後的數據
 */
- (nullable NSString *)cachedFileNameForKey:(nullable NSString *)key {
    const char *str = key.UTF8String;
    if (str == NULL) {
        str = "";
    }
    unsigned char r[CC_MD5_DIGEST_LENGTH];
    CC_MD5(str, (CC_LONG)strlen(str), r);
    NSString *filename = [NSString stringWithFormat:@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%@",
                          r[0], r[1], r[2], r[3], r[4], r[5], r[6], r[7], r[8], r[9], r[10],
                          r[11], r[12], r[13], r[14], r[15], [key.pathExtension isEqualToString:@""] ? @"" : [NSString stringWithFormat:@".%@", key.pathExtension]];

    return filename;
}

/**
 圖片緩存目錄

 @param fullNamespace 自定義目錄
 @return 完整目錄
 */
- (nullable NSString *)makeDiskCachePath:(nonnull NSString*)fullNamespace {
    NSArray<NSString *> *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    return [paths[0] stringByAppendingPathComponent:fullNamespace];
}

#pragma mark - 圖片緩存具體實現的一些列方法

- (void)storeImage:(nullable UIImage *)image
            forKey:(nullable NSString *)key
        completion:(nullable SDWebImageNoParamsBlock)completionBlock {
    [self storeImage:image imageData:nil forKey:key toDisk:YES completion:completionBlock];
}

- (void)storeImage:(nullable UIImage *)image
            forKey:(nullable NSString *)key
            toDisk:(BOOL)toDisk
        completion:(nullable SDWebImageNoParamsBlock)completionBlock {
    [self storeImage:image imageData:nil forKey:key toDisk:toDisk completion:completionBlock];
}

/**
 把一張圖片存入緩存的具體實現

 @param image 緩存的圖片對象
 @param imageData 緩存的圖片數據
 @param key 緩存對應的key
 @param toDisk 是否緩存到瓷片
 @param completionBlock 緩存完成回調
 */
- (void)storeImage:(nullable UIImage *)image
         imageData:(nullable NSData *)imageData
            forKey:(nullable NSString *)key
            toDisk:(BOOL)toDisk
        completion:(nullable SDWebImageNoParamsBlock)completionBlock {
    if (!image || !key) {
        if (completionBlock) {
            completionBlock();
        }
        return;
    }
    //緩存到內存
    if (self.config.shouldCacheImagesInMemory) {
        //計算緩存數據的大小
        NSUInteger cost = SDCacheCostForImage(image);
        //加入緩存對此昂
        [self.memCache setObject:image forKey:key cost:cost];
    }
    
    if (toDisk) {
        /*
         在一個線性隊列中作磁盤緩存操做。
         */
        dispatch_async(self.ioQueue, ^{
            NSData *data = imageData;
            if (!data && image) {
                //獲取圖片的類型GIF/PNG等
                SDImageFormat imageFormatFromData = [NSData sd_imageFormatForImageData:data];
                //根據指定的SDImageFormat。把圖片轉換爲對應的data數據
                data = [image sd_imageDataAsFormat:imageFormatFromData];
            }
            //把處理好了的數據存入磁盤
            [self storeImageDataToDisk:data forKey:key];
            if (completionBlock) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    completionBlock();
                });
            }
        });
    } else {
        if (completionBlock) {
            completionBlock();
        }
    }
}

/**
 把圖片資源存入磁盤

 @param imageData 圖片數據
 @param key key
 */
- (void)storeImageDataToDisk:(nullable NSData *)imageData forKey:(nullable NSString *)key {
    if (!imageData || !key) {
        return;
    }
    
    [self checkIfQueueIsIOQueue];
    //緩存目錄是否已經初始化
    if (![_fileManager fileExistsAtPath:_diskCachePath]) {
        [_fileManager createDirectoryAtPath:_diskCachePath withIntermediateDirectories:YES attributes:nil error:NULL];
    }
    
    // get cache Path for image key
    //獲取key對應的完整緩存路徑
    NSString *cachePathForKey = [self defaultCachePathForKey:key];
    // transform to NSUrl
    NSURL *fileURL = [NSURL fileURLWithPath:cachePathForKey];
    //把數據存入路徑
    [_fileManager createFileAtPath:cachePathForKey contents:imageData attributes:nil];
    
    // disable iCloud backup
    if (self.config.shouldDisableiCloud) {
        //給文件添加到運行存儲到iCloud屬性
        [fileURL setResourceValue:@YES forKey:NSURLIsExcludedFromBackupKey error:nil];
    }
}

#pragma mark - Query and Retrieve Ops

- (void)diskImageExistsWithKey:(nullable NSString *)key completion:(nullable SDWebImageCheckCacheCompletionBlock)completionBlock {
    dispatch_async(_ioQueue, ^{
        BOOL exists = [_fileManager fileExistsAtPath:[self defaultCachePathForKey:key]];

        // fallback because of https://github.com/rs/SDWebImage/pull/976 that added the extension to the disk file name
        // checking the key with and without the extension
        if (!exists) {
            exists = [_fileManager fileExistsAtPath:[self defaultCachePathForKey:key].stringByDeletingPathExtension];
        }

        if (completionBlock) {
            dispatch_async(dispatch_get_main_queue(), ^{
                completionBlock(exists);
            });
        }
    });
}

/**
 根據key獲取緩存在內存中的圖片

 @param key key
 @return 緩存的圖片
 */
- (nullable UIImage *)imageFromMemoryCacheForKey:(nullable NSString *)key {
    return [self.memCache objectForKey:key];
}

- (nullable UIImage *)imageFromDiskCacheForKey:(nullable NSString *)key {
    UIImage *diskImage = [self diskImageForKey:key];
    if (diskImage && self.config.shouldCacheImagesInMemory) {
        NSUInteger cost = SDCacheCostForImage(diskImage);
        [self.memCache setObject:diskImage forKey:key cost:cost];
    }

    return diskImage;
}

- (nullable UIImage *)imageFromCacheForKey:(nullable NSString *)key {
    // First check the in-memory cache...
    UIImage *image = [self imageFromMemoryCacheForKey:key];
    if (image) {
        return image;
    }
    
    // Second check the disk cache...
    image = [self imageFromDiskCacheForKey:key];
    return image;
}

/**
 根據指定的key,獲取存儲在磁盤上的數據

 @param key 圖片對應的key
 @return 返回圖片數據
 */
- (nullable NSData *)diskImageDataBySearchingAllPathsForKey:(nullable NSString *)key {
    //獲取key對應的path
    NSString *defaultPath = [self defaultCachePathForKey:key];
    NSData *data = [NSData dataWithContentsOfFile:defaultPath];
    if (data) {
        return data;
    }

    // fallback because of https://github.com/rs/SDWebImage/pull/976 that added the extension to the disk file name
    // checking the key with and without the extension
    /*
     若是key麼有後綴名,則會走到這裏經過這裏讀取
     */
    data = [NSData dataWithContentsOfFile:defaultPath.stringByDeletingPathExtension];
    if (data) {
        return data;
    }
    /*
     若是在默認路徑沒有找到圖片,則在自定義路徑迭代查找
     */
    NSArray<NSString *> *customPaths = [self.customPaths copy];
    for (NSString *path in customPaths) {
        NSString *filePath = [self cachePathForKey:key inPath:path];
        NSData *imageData = [NSData dataWithContentsOfFile:filePath];
        if (imageData) {
            return imageData;
        }

        // fallback because of https://github.com/rs/SDWebImage/pull/976 that added the extension to the disk file name
        // checking the key with and without the extension
        imageData = [NSData dataWithContentsOfFile:filePath.stringByDeletingPathExtension];
        if (imageData) {
            return imageData;
        }
    }

    return nil;
}

/**
 根據指定的key獲取image對象

 @param key key
 @return image對象
 */
- (nullable UIImage *)diskImageForKey:(nullable NSString *)key {
    //獲取磁盤數據
    NSData *data = [self diskImageDataBySearchingAllPathsForKey:key];
    if (data) {
        UIImage *image = [UIImage sd_imageWithData:data];
        image = [self scaledImageForKey:key image:image];
        if (self.config.shouldDecompressImages) {
            image = [UIImage decodedImageWithImage:image];
        }
        return image;
    }
    else {
        return nil;
    }
}

- (nullable UIImage *)scaledImageForKey:(nullable NSString *)key image:(nullable UIImage *)image {
    return SDScaledImageForKey(key, image);
}

/**
 在緩存中查詢對應key的數據。經過一個NSOperation來完成

 @param key 要查詢的key
 @param doneBlock 查詢結束之後的Block
 @return 返回作查詢操做的Block
 */
- (nullable NSOperation *)queryCacheOperationForKey:(nullable NSString *)key done:(nullable SDCacheQueryCompletedBlock)doneBlock {
    if (!key) {
        if (doneBlock) {
            doneBlock(nil, nil, SDImageCacheTypeNone);
        }
        return nil;
    }
    // First check the in-memory cache...
    //首先從內測中查找圖片
    UIImage *image = [self imageFromMemoryCacheForKey:key];
    if (image) {
        NSData *diskData = nil;
        //是不是gif圖片
        if ([image isGIF]) {
            diskData = [self diskImageDataBySearchingAllPathsForKey:key];
        }
        if (doneBlock) {
            doneBlock(image, diskData, SDImageCacheTypeMemory);
        }
        return nil;
    }
    //新建一個NSOperation來獲取磁盤圖片
    NSOperation *operation = [NSOperation new];
    dispatch_async(self.ioQueue, ^{
        if (operation.isCancelled) {
            // do not call the completion if cancelled
            return;
        }
        //在一個自動釋放池中處理圖片從磁盤加載
        @autoreleasepool {
            NSData *diskData = [self diskImageDataBySearchingAllPathsForKey:key];
            UIImage *diskImage = [self diskImageForKey:key];
            if (diskImage && self.config.shouldCacheImagesInMemory) {
                NSUInteger cost = SDCacheCostForImage(diskImage);
                //把從磁盤取出的緩存圖片加入內存緩存中
                [self.memCache setObject:diskImage forKey:key cost:cost];
            }
            //圖片處理完成之後回調Block
            if (doneBlock) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    doneBlock(diskImage, diskData, SDImageCacheTypeDisk);
                });
            }
        }
    });
    return operation;
}

#pragma mark - Remove Ops

- (void)removeImageForKey:(nullable NSString *)key withCompletion:(nullable SDWebImageNoParamsBlock)completion {
    [self removeImageForKey:key fromDisk:YES withCompletion:completion];
}

/**
 移除指定key對應的緩存數據

 @param key key
 @param fromDisk 是否也清除磁盤緩存
 @param completion 回調
 */
- (void)removeImageForKey:(nullable NSString *)key fromDisk:(BOOL)fromDisk withCompletion:(nullable SDWebImageNoParamsBlock)completion {
    if (key == nil) {
        return;
    }
    //移除內存緩存
    if (self.config.shouldCacheImagesInMemory) {
        [self.memCache removeObjectForKey:key];
    }
    //移除磁盤緩存
    if (fromDisk) {
        dispatch_async(self.ioQueue, ^{
            [_fileManager removeItemAtPath:[self defaultCachePathForKey:key] error:nil];
            
            if (completion) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    completion();
                });
            }
        });
    } else if (completion){
        completion();
    }
    
}

# pragma mark - Mem Cache settings

- (void)setMaxMemoryCost:(NSUInteger)maxMemoryCost {
    self.memCache.totalCostLimit = maxMemoryCost;
}

- (NSUInteger)maxMemoryCost {
    return self.memCache.totalCostLimit;
}

- (NSUInteger)maxMemoryCountLimit {
    return self.memCache.countLimit;
}

- (void)setMaxMemoryCountLimit:(NSUInteger)maxCountLimit {
    self.memCache.countLimit = maxCountLimit;
}

#pragma mark - 內存緩存清理相關操做

/**
 清理當前SDImageCache對象的內存緩存
 */
- (void)clearMemory {
    [self.memCache removeAllObjects];
}

/**
 移除全部的緩存圖片數據

 @param completion 移除完成之後回調
 */
- (void)clearDiskOnCompletion:(nullable SDWebImageNoParamsBlock)completion {
    dispatch_async(self.ioQueue, ^{
        [_fileManager removeItemAtPath:self.diskCachePath error:nil];
        [_fileManager createDirectoryAtPath:self.diskCachePath
                withIntermediateDirectories:YES
                                 attributes:nil
                                      error:NULL];
        if (completion) {
            dispatch_async(dispatch_get_main_queue(), ^{
                completion();
            });
        }
    });
}

- (void)deleteOldFiles {
    [self deleteOldFilesWithCompletionBlock:nil];
}

/**
 當應用終止或者進入後臺都回調用這個方法來清除緩存圖片。
 這裏會根據圖片存儲時間來清理圖片、默認是一週,從最老的圖片開始清理。若是圖片緩存空間小於一個規定值,則不考慮。

 @param completionBlock 清除完成之後的回調
 */
- (void)deleteOldFilesWithCompletionBlock:(nullable SDWebImageNoParamsBlock)completionBlock {
    dispatch_async(self.ioQueue, ^{
        //獲取磁盤緩存的默認根目錄
        NSURL *diskCacheURL = [NSURL fileURLWithPath:self.diskCachePath isDirectory:YES];
        
        NSArray<NSString *> *resourceKeys = @[NSURLIsDirectoryKey, NSURLContentModificationDateKey, NSURLTotalFileAllocatedSizeKey];

        // This enumerator prefetches useful properties for our cache files.
        /*
         第二個參數制定了須要獲取的屬性集合
         第三個參數表示不迭代隱藏文件
        */
        NSDirectoryEnumerator *fileEnumerator = [_fileManager enumeratorAtURL:diskCacheURL
                                                   includingPropertiesForKeys:resourceKeys
                                                                      options:NSDirectoryEnumerationSkipsHiddenFiles
                                                                 errorHandler:NULL];

        NSDate *expirationDate = [NSDate dateWithTimeIntervalSinceNow:-self.config.maxCacheAge];
        NSMutableDictionary<NSURL *, NSDictionary<NSString *, id> *> *cacheFiles = [NSMutableDictionary dictionary];
        NSUInteger currentCacheSize = 0;

        // Enumerate all of the files in the cache directory.  This loop has two purposes:
        //
        //  1. Removing files that are older than the expiration date.
        //  2. Storing file attributes for the size-based cleanup pass.
        /*
         迭代緩存目錄。有兩個目的:
         1 刪除比指定日期更老的圖片
         2 記錄文件的大小,以提供給後面刪除使用
         */
        NSMutableArray<NSURL *> *urlsToDelete = [[NSMutableArray alloc] init];
        for (NSURL *fileURL in fileEnumerator) {
            NSError *error;
            //獲取指定url對應文件的指定三種屬性的key和value
            NSDictionary<NSString *, id> *resourceValues = [fileURL resourceValuesForKeys:resourceKeys error:&error];
            // Skip directories and errors.
            //若是是文件夾則返回
            if (error || !resourceValues || [resourceValues[NSURLIsDirectoryKey] boolValue]) {
                continue;
            }

            // Remove files that are older than the expiration date;
            //獲取指定url文件對應的修改日期
            NSDate *modificationDate = resourceValues[NSURLContentModificationDateKey];
            //若是修改日期大於指定日期,則加入要移除的數組裏
            if ([[modificationDate laterDate:expirationDate] isEqualToDate:expirationDate]) {
                [urlsToDelete addObject:fileURL];
                continue;
            }

            // Store a reference to this file and account for its total size.
            //獲取指定的url對應的文件的大小,而且把url與對應大小存入一個字典中
            NSNumber *totalAllocatedSize = resourceValues[NSURLTotalFileAllocatedSizeKey];
            currentCacheSize += totalAllocatedSize.unsignedIntegerValue;
            cacheFiles[fileURL] = resourceValues;
        }
        //刪除全部最後修改日期大於指定日期的全部文件
        for (NSURL *fileURL in urlsToDelete) {
            [_fileManager removeItemAtURL:fileURL error:nil];
        }

        // If our remaining disk cache exceeds a configured maximum size, perform a second
        // size-based cleanup pass.  We delete the oldest files first.
        /*
         若是咱們當前緩存的大小超過了默認大小,則按照日期刪除,直到緩存大小<默認大小的一半
         */
        if (self.config.maxCacheSize > 0 && currentCacheSize > self.config.maxCacheSize) {
            // Target half of our maximum cache size for this cleanup pass.
            const NSUInteger desiredCacheSize = self.config.maxCacheSize / 2;

            // Sort the remaining cache files by their last modification time (oldest first).
            //根據文件建立的時間排序
            NSArray<NSURL *> *sortedFiles = [cacheFiles keysSortedByValueWithOptions:NSSortConcurrent
                                                                     usingComparator:^NSComparisonResult(id obj1, id obj2) {
                                                                         return [obj1[NSURLContentModificationDateKey] compare:obj2[NSURLContentModificationDateKey]];
                                                                     }];

            // Delete files until we fall below our desired cache size.
            /*
             迭代刪除緩存,直到緩存大小是默認緩存大小的一半
             */
            for (NSURL *fileURL in sortedFiles) {
                if ([_fileManager removeItemAtURL:fileURL error:nil]) {
                    NSDictionary<NSString *, id> *resourceValues = cacheFiles[fileURL];
                    NSNumber *totalAllocatedSize = resourceValues[NSURLTotalFileAllocatedSizeKey];
                    //總得緩存大小減去當前要刪除文件的大小
                    currentCacheSize -= totalAllocatedSize.unsignedIntegerValue;

                    if (currentCacheSize < desiredCacheSize) {
                        break;
                    }
                }
            }
        }
        //執行完畢,主線程回調
        if (completionBlock) {
            dispatch_async(dispatch_get_main_queue(), ^{
                completionBlock();
            });
        }
    });
}

#if SD_UIKIT

/**
 應用進入後臺的時候,調用這個方法
 */
- (void)backgroundDeleteOldFiles {
    Class UIApplicationClass = NSClassFromString(@"UIApplication");
    if(!UIApplicationClass || ![UIApplicationClass respondsToSelector:@selector(sharedApplication)]) {
        return;
    }
    UIApplication *application = [UIApplication performSelector:@selector(sharedApplication)];
    //若是backgroundTask對應的時間結束了。任務還麼有處理完成。則直接終止任務
    __block UIBackgroundTaskIdentifier bgTask = [application beginBackgroundTaskWithExpirationHandler:^{
        // Clean up any unfinished task business by marking where you
        // stopped or ending the task outright.
        //當任務非正常終止的時候,作清理工做
        [application endBackgroundTask:bgTask];
        bgTask = UIBackgroundTaskInvalid;
    }];

    // Start the long-running task and return immediately.
    //圖片清理結束之後。處理完成
    [self deleteOldFilesWithCompletionBlock:^{
        //清理完成之後,終止任務
        [application endBackgroundTask:bgTask];
        bgTask = UIBackgroundTaskInvalid;
    }];
}
#endif

#pragma mark - Cache Info

- (NSUInteger)getSize {
    __block NSUInteger size = 0;
    dispatch_sync(self.ioQueue, ^{
        NSDirectoryEnumerator *fileEnumerator = [_fileManager enumeratorAtPath:self.diskCachePath];
        for (NSString *fileName in fileEnumerator) {
            NSString *filePath = [self.diskCachePath stringByAppendingPathComponent:fileName];
            NSDictionary<NSString *, id> *attrs = [[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:nil];
            size += [attrs fileSize];
        }
    });
    return size;
}

- (NSUInteger)getDiskCount {
    __block NSUInteger count = 0;
    dispatch_sync(self.ioQueue, ^{
        NSDirectoryEnumerator *fileEnumerator = [_fileManager enumeratorAtPath:self.diskCachePath];
        count = fileEnumerator.allObjects.count;
    });
    return count;
}

- (void)calculateSizeWithCompletionBlock:(nullable SDWebImageCalculateSizeBlock)completionBlock {
    NSURL *diskCacheURL = [NSURL fileURLWithPath:self.diskCachePath isDirectory:YES];

    dispatch_async(self.ioQueue, ^{
        NSUInteger fileCount = 0;
        NSUInteger totalSize = 0;

        NSDirectoryEnumerator *fileEnumerator = [_fileManager enumeratorAtURL:diskCacheURL
                                                   includingPropertiesForKeys:@[NSFileSize]
                                                                      options:NSDirectoryEnumerationSkipsHiddenFiles
                                                                 errorHandler:NULL];

        for (NSURL *fileURL in fileEnumerator) {
            NSNumber *fileSize;
            [fileURL getResourceValue:&fileSize forKey:NSURLFileSizeKey error:NULL];
            totalSize += fileSize.unsignedIntegerValue;
            fileCount += 1;
        }

        if (completionBlock) {
            dispatch_async(dispatch_get_main_queue(), ^{
                completionBlock(fileCount, totalSize);
            });
        }
    });
}
@end

最後原文地址.html),demo地址

相關文章
相關標籤/搜索