SDWebImage源码解析

时间:2022-03-29 05:03:10

但凡经过几年移动开发经验的人去大公司面试,都会有公司问到,使用过哪些第三方,看过他们的源码嘛?而SDWebImage就是经常被面试官和应聘者的提到的。下面将讲述SDWebImage的源码解析以及实现原理,希望可以帮助大家加深对SDWebImage实现原理的理解!!!

一、前言

SDWebImage专门用于iOS图片加载框架,提供了网络下载并缓存图片,通过使用SDWebImage来管理图片的相关操作,从而让研发人员专注业务逻辑实现,提高开发效率。

首先我们来看一下它的代码的整体结构。

SDWebImage源码解析

看过上面的整体结构之后,紧接着看下代码的构成和分类,以及各个类的作用

SDWebImage源码解析

通过以上代码结构划分,可以看出SDWebImage是非常强大的,我们平常用到的不过是冰山一角。

那么SDWebImage的功能有哪些呢。

  1. 提供UIImageView的category用来加载和缓存网络图片。
  2. 提供异步方式下载网络图片。
  3. 提供GIF动画。
  4. 提供同一个URL的网络图片不会被重新下载两次。
  5. 支持Arm64。
  6. 耗时放在子线程,确保不会阻塞主线程。

二、概述

整个下载图片的过程如下:

  1. 入口 setImageWithURL:placeholderImage:options:会先将placeholderImage显示,然后使用SDWebImageManager根据URL来处理图片;
  2. 随之调用SDWebImageManagerdownloadWithURL:delegate:options:userInfo:,紧接着交给SDImageCache从缓存里面查找是否下载了,调用queryDiskCacheForKey:delegate:
  3. 先从内存缓存中查找是否有该图片,如果内存有该图片,SDImageCacheDelegate中回调imageCache:didFindImage
  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:方法来回调给SDWebImageDownloader来检测图片是否已经下载完成了。
  16. 紧着发通知给所有的downloadDelegates下载完成,进而回调给需要的地方展示。
  17. 将图片保存到SDImageCache中,同时也会加入内存缓存和硬盘缓存中,写文件到硬盘中是在NSInvocationOperation中完成的,为了避免阻塞主线程。
  18. 在初始化的时候会注册消息通知,遇到内存警告或者退到后台会清理内存管理缓存,应用结束的时候清理过期图片。

三、代码解析

3.1 .SDWebImageManager

SDWebImageManager是拥有一个SDWebImageCache和SDWebImageDownloader两个属性分别用于图片的缓存和下载需求。

我们经常使用的UIImageView以及其他视图通过UIView+WebCache分类的sd_internalSetImageWithURL来调用SDWebImageManager类实现图片加载。

3.1.1 下面这个方法是核心方法。

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

下面我们看一下实现方法

@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 == || (!(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 = ;
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, ), ^{
//获取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;
}

3.1.2 SDWebImageCombinedOperation

loadImageWithURL方法会返回一个对象,该对象又个cancel方法,方法继承自SDWebImageOperation协议。

/**
通过这个对象关联一个`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

如果我们在操作中,取消是放在UIView+WebCache中。

- (void)sd_cancelCurrentImageLoad {
[self sd_cancelImageLoadOperationWithKey:NSStringFromClass([self class])];
} /**
取消当前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.2 SDImageCache

3.2.1 SDImageCache总结

SDImageCache主要是通过NSCache来管理内存以及根据传入的key转换为MD5作为文件存储。SDWebImageManager也是通过SDImageCache来获取和存储图片的,并且SDImageCache是一个单例对象。总结如下:

  1. 通过AutoPurgeCache(也是NSCache的子类)来管理内存缓存。当收到内存警告的时候,移除内存中所有的对象。
  2. 如果接收到UIApplicationDidReceiveMemoryWarningNotification之后,会删除内存中所有的缓存图片。
  3. 如果接收到UIApplicationWillTerminateNotification通知后,会通过deleteOldFiles方法删除比较老的图片。下面是删除的具体细则:
    • 通过SDImageCacheConfig来设置缓存大小,过期日期以及是否允许缓存
    • 第一会根据迭代缓存目录下的所有文件,如果大于一周的图片会全部删除。
    • 然后会记录缓存目录的大小,如果当前缓存大于默认缓存,会按照创建日期的先后开始删除图片缓存,直到缓存小于默认缓存大小。
  4. 当接到UIApplicationDidEnterBackgroundNotification通知之后,此时会调用deleteOldFilesWithCompletionBlock方法用于清除缓存数据。
  5. 也定义了方法用于处理图片的获取,缓存以及其他工作。
    • 通过queryCacheOperationForKey方法查询指定的key,查找对应的缓存图片,再从内存,硬盘中找。
    • 通过removeImageForKey方法移除指定的缓存图片。
    • 通过diskImageDataBySearchingAllPathsForKey方法在磁盘查找key对应的图片。
    • 通过storeImageDataToDisk方法把指定的图片数据存入磁盘。
  6. 通过cachedFileNameForKey方法获取图片对应的MD5加密的缓存名字。

3.2.2 具体方法

看完上面的些许总结:下面看一下SDWebImageCache的具体方法。

1.初始化方法

//单例
+ (nonnull instancetype)sharedImageCache; //初始化一个namespace空间
- (nonnull instancetype)initWithNamespace:(nonnull NSString *)ns; //初始化一个namespace空间和存储的路径
- (nonnull instancetype)initWithNamespace:(nonnull NSString *)ns
diskCacheDirectory:(nonnull NSString *)directory NS_DESIGNATED_INITIALIZER;

下面是实现方式

//创建单例模式
+ (nonnull instancetype)sharedImageCache {
static dispatch_once_t once;
static id instance;
dispatch_once(&once, ^{
instance = [self new];
});
return instance;
} //
- (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]; // Create IO serial queue
_ioQueue = dispatch_queue_create("com.hackemist.SDWebImageCache", DISPATCH_QUEUE_SERIAL); _config = [[SDImageCacheConfig alloc] init]; // Init the memory cache
_memCache = [[AutoPurgeCache alloc] init];
_memCache.name = fullNamespace; // Init the disk cache
if (directory != nil) {
_diskCachePath = [directory stringByAppendingPathComponent:fullNamespace];
} else {
NSString *path = [self makeDiskCachePath:ns];
_diskCachePath = path;
} dispatch_sync(_ioQueue, ^{
_fileManager = [NSFileManager new];
}); #if SD_UIKIT
// Subscribe to app events
[[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;
}

可以看一下上面总结的,以及上面实现代码中- (nonnull instancetype)initWithNamespace:(nonnull NSString *)ns diskCacheDirectory:(nonnull NSString *)directory 标红的,就知道方法的调用过程。

2.存储路径

//存储路径
- (nullable NSString *)makeDiskCachePath:(nonnull NSString*)fullNamespace; //添加只读cache的path
- (void)addReadOnlyCachePath:(nonnull NSString *)path;

下面看一下实现方法

#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];
}
} - (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];
} - (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);
NSURL *keyURL = [NSURL URLWithString:key];
NSString *ext = keyURL ? keyURL.pathExtension : key.pathExtension;
NSString *filename = [NSString stringWithFormat:@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%@",
r[], r[], r[], r[], r[], r[], r[], r[], r[], r[], r[],
r[], r[], r[], r[], r[], ext.length == ? @"" : [NSString stringWithFormat:@".%@", ext]];
return filename;
} - (nullable NSString *)makeDiskCachePath:(nonnull NSString*)fullNamespace {
NSArray<NSString *> *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
return [paths[] stringByAppendingPathComponent:fullNamespace];
}

3.存储图片

存储图片主要分为两模块

  1. 存储到内存:直接计算图片大小之后,然后用NSCache *memCache存储
  2. 存储到硬盘:首先将UIImage转化为NSData,然后用NSFileManager *_fileManager创建存储文件路径和图片存储文件

下面是存储图片的几个方法

//存储image到key
- (void)storeImage:(nullable UIImage *)image
forKey:(nullable NSString *)key
completion:(nullable SDWebImageNoParamsBlock)completionBlock; //存储image到key,是否硬盘缓存
- (void)storeImage:(nullable UIImage *)image
forKey:(nullable NSString *)key
toDisk:(BOOL)toDisk
completion:(nullable SDWebImageNoParamsBlock)completionBlock; //存储imageData到key,是否硬盘缓存
- (void)storeImage:(nullable UIImage *)image
imageData:(nullable NSData *)imageData
forKey:(nullable NSString *)key
toDisk:(BOOL)toDisk
completion:(nullable SDWebImageNoParamsBlock)completionBlock; //硬盘缓存,key
- (void)storeImageDataToDisk:(nullable NSData *)imageData forKey:(nullable NSString *)key;

下面看一下具体实现的过程

- (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];
} - (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 memory cache is enabled
if (self.config.shouldCacheImagesInMemory) {
NSUInteger cost = SDCacheCostForImage(image);
[self.memCache setObject:image forKey:key cost:cost];
} if (toDisk) {
dispatch_async(self.ioQueue, ^{
@autoreleasepool {
NSData *data = imageData;
if (!data && image) {
// If we do not have any data to detect image format, check whether it contains alpha channel to use PNG or JPEG format
SDImageFormat format;
if (SDCGImageRefContainsAlpha(image.CGImage)) {
format = SDImageFormatPNG;
} else {
format = SDImageFormatJPEG;
}
data = [[SDWebImageCodersManager sharedInstance] encodedDataWithImage:image format:format];
}
[self storeImageDataToDisk:data forKey:key];
} if (completionBlock) {
dispatch_async(dispatch_get_main_queue(), ^{
completionBlock();
});
}
});
} else {
if (completionBlock) {
completionBlock();
}
}
} - (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
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) {
[fileURL setResourceValue:@YES forKey:NSURLIsExcludedFromBackupKey error:nil];
}
}

4.读取图片

读取图片分为从内存里面和从硬盘图片读取。

- (void)diskImageExistsWithKey:(nullable NSString *)key completion:(nullable SDWebImageCheckCacheCompletionBlock)completionBlock;

- (nullable NSOperation *)queryCacheOperationForKey:(nullable NSString *)key done:(nullable SDCacheQueryCompletedBlock)doneBlock;

- (nullable UIImage *)imageFromMemoryCacheForKey:(nullable NSString *)key;

- (nullable UIImage *)imageFromDiskCacheForKey:(nullable NSString *)key;

- (nullable UIImage *)imageFromCacheForKey:(nullable NSString *)key;

下面是实现方法

- (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);
});
}
});
} - (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;
} - (nullable NSData *)diskImageDataBySearchingAllPathsForKey:(nullable NSString *)key {
NSString *defaultPath = [self defaultCachePathForKey:key];
NSData *data = [NSData dataWithContentsOfFile:defaultPath options:self.config.diskCacheReadingOptions error:nil];
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
data = [NSData dataWithContentsOfFile:defaultPath.stringByDeletingPathExtension options:self.config.diskCacheReadingOptions error:nil];
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 options:self.config.diskCacheReadingOptions error:nil];
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 options:self.config.diskCacheReadingOptions error:nil];
if (imageData) {
return imageData;
}
} return nil;
} - (nullable UIImage *)diskImageForKey:(nullable NSString *)key {
NSData *data = [self diskImageDataBySearchingAllPathsForKey:key];
if (data) {
UIImage *image = [[SDWebImageCodersManager sharedInstance] decodedImageWithData:data];
image = [self scaledImageForKey:key image:image];
if (self.config.shouldDecompressImages) {
image = [[SDWebImageCodersManager sharedInstance] decompressedImageWithImage:image data:&data options:@{SDWebImageCoderScaleDownLargeImagesKey: @(NO)}];
}
return image;
} else {
return nil;
}
} - (nullable UIImage *)scaledImageForKey:(nullable NSString *)key image:(nullable UIImage *)image {
return SDScaledImageForKey(key, image);
} - (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;
if (image.images) {
diskData = [self diskImageDataBySearchingAllPathsForKey:key];
}
if (doneBlock) {
doneBlock(image, diskData, SDImageCacheTypeMemory);
}
return nil;
} 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];
} if (doneBlock) {
dispatch_async(dispatch_get_main_queue(), ^{
doneBlock(diskImage, diskData, SDImageCacheTypeDisk);
});
}
}
}); return operation;
}

5.删除图片

删除图片分为两步;首先从cache删除缓存图片,然后再从硬盘删除对应的文件。

- (void)removeImageForKey:(nullable NSString *)key withCompletion:(nullable SDWebImageNoParamsBlock)completion;

- (void)removeImageForKey:(nullable NSString *)key fromDisk:(BOOL)fromDisk withCompletion:(nullable SDWebImageNoParamsBlock)completion;

下面是删除图片的实现代码

- (void)removeImageForKey:(nullable NSString *)key withCompletion:(nullable SDWebImageNoParamsBlock)completion {
[self removeImageForKey:key fromDisk:YES withCompletion: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();
} }

6.清理缓存

下面是清理缓存分为两步:首先清除所有过期图片,然后

//Clear all memory cached images
- (void)clearMemory; //clear all disk cached images
- (void)clearDiskOnCompletion:(nullable SDWebImageNoParamsBlock)completion; //remove all expired cached image from disk.
- (void)deleteOldFilesWithCompletionBlock:(nullable SDWebImageNoParamsBlock)completionBlock;

下面是实现方式

- (void)clearMemory {
[self.memCache removeAllObjects];
} - (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];
} - (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 = ; // 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.
NSMutableArray<NSURL *> *urlsToDelete = [[NSMutableArray alloc] init];
for (NSURL *fileURL in fileEnumerator) {
NSError *error;
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;
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.
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 > && currentCacheSize > self.config.maxCacheSize) {
// Target half of our maximum cache size for this cleanup pass.
const NSUInteger desiredCacheSize = self.config.maxCacheSize / ; // 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();
});
}
});
}

3.3 SDWebImageDownloader

SDWebImageManager通过imageDownloader属性持有SDWebImageDownloader对象,并且可以调用它的downloadImageWithURL方法来从加载图片。

对于SDWebImageDownloader具体做了哪些工作如下。

SDWebImageManager是一个单例对象,做如下工作:

  1. 定义SDWebImageDownloaderOptions属性(枚举属性)通过这个属性来设置从网络加载的不同状况。
  2. 定义管理NSURLSession对象,用这个对象做网络请求,实现对象的代理方法。
  3. 新建一个NSURLRequest对象,管理请求头的拼接。
  4. 对于每个请求,通过SDWebImageDownloaderOperation对象来操作网络下载。
  5. 管理网络下载和完成的回调工作,通过addProgressCallback方法实现。

3.4 SDWebImageDownloaderOperation

SDWebImageDownloaderOperation主要功能:

  1. SDWebImageDownloaderOperation是NSOperation子类,在start方法里面实现逻辑。
  2. NSURLSessionTaskDelegate和NSURLSessionDataDelegate来处理数据加载,以及进度的处理。
  3. 如果unownedSession为nil时,则初始化一个网络请求
  4. 发送SDWebImageDownloadStopNotification,SDWebImageDownloadStartNotification,SDWebImageDownloadFinishNotification,SDWebImageDownloadReceiveResponseNotification等通知,来通知Operation的状态。

SDWebImage主要的内容就是上面,当然还有一些辅助方法,大家可以不需要了解,看一下上面内容就会明白SDWebImage底层实现的逻辑。欢迎大家指正(后期会不断的更新)。