SDWebImage是现在最好用也是用的最广泛的网络图片下载第三方库,内部封装很好,非常值得学习,现整理如下。文中有部分内容来自于作者 Haley_Wong的SDWebImageV3.7.5源码解析。
代码详解
SDWebImage通过添加category的方式,为UIImageView、UIButton扩展设置网络图片的方法。以UIImageView举例,其包含如下设置图片的方法:
- (void)sd_setImageWithURL:(NSURL *)url;
- (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder;
- (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options;
- (void)sd_setImageWithURL:(NSURL *)url completed:(SDWebImageCompletionBlock)completedBlock;
- (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletionBlock)completedBlock;
- (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletionBlock)completedBlock;
- (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletionBlock)completedBlock;
- (void)sd_setImageWithPreviousCachedImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletionBlock)completedBlock;
- (void)sd_setAnimationImagesWithURLs:(NSArray *)arrayOfURLs;
如上这些方法,最终都是调用各category中的方法:
- (id )downloadImageWithURL:(NSURL *)url
options:(SDWebImageOptions)options
progress:(SDWebImageDownloaderProgressBlock)progressBlock
completed:(SDWebImageCompletionWithFinishedBlock)completedBlock;
每个category中的该方法具体逻辑不尽相同,这里以UIImageView为例,其内部的逻辑大体为:
1.取消该UIImageView的当前图片加载操作。(重点一)
2.利用runtime的关联对象AssociatedObject为该UIImageView设置网络图片的url,可以通过方法- (NSURL *)sd_imageURL;
来获取该对象的URL。(runtime的使用场景)
3.设置默认图片。(即placeholder,若设置了延迟设置placeholder,则跳过该步)
4.判断url是否存在,不存在则回调completedBlock,返回错误信息;若存在,执行下一步。
5.判断是否添加ActivityIndicatorView。
6.调用SDWebImageManager,创建下载图片的operation。(重点二,SDWebImage的核心内容)
7.为该UIImageView设置下载的operation。(同样是通过runtime的关联对象AssociatedObject实现)
8.执行下载完成的completedBlock回调。(这一步也值得详细解析)
重点一
取消UIImageView的当前图片加载操作。为什么需要取消当前加载操作呢?假如某一对象(UIImageView *
)设置了多个网络图片时,因为下载过程是异步的,假如不取消前一下载操作,那么最终得到的图片很可能是错误的。且浪费流量及资源。
- (void)sd_cancelCurrentImageLoad {
[self sd_cancelImageLoadOperationWithKey:@"UIImageViewImageLoad"];
}
- (void)sd_cancelCurrentAnimationImagesLoad {
[self sd_cancelImageLoadOperationWithKey:@"UIImageViewAnimationImages"];
}
可以看到,这里有两个不同的取消方法,因为UIImageView除了可以设置单张图片,还可以设置多张网络图片展示动画效果。这两个方法内部调用的是同一个方法:
- (void)sd_cancelImageLoadOperationWithKey:(NSString *)key {
// Cancel in progress downloader from queue
NSMutableDictionary *operationDictionary = [self operationDictionary];
id operations = [operationDictionary objectForKey:key];
if (operations) {
if ([operations isKindOfClass:[NSArray class]]) {
for (id operation in operations) {
if (operation) {
[operation cancel];
}
}
} else if ([operations conformsToProtocol:@protocol(SDWebImageOperation)]){
[(id) operations cancel];
}
[operationDictionary removeObjectForKey:key];
}
}
上面这个方法是UIView的一个category方法,在UIView + WebCacheOperation
中。其中[self operationDictionary]
利用runtime
的关联对象(AssociatedObject
)获取当前视图的operationDictionary,没有的话就创建一个set上去,具体实现如下:
- (NSMutableDictionary *)operationDictionary {
//获取关联对象
NSMutableDictionary *operations = objc_getAssociatedObject(self, &loadOperationKey);
if (operations) {
return operations;
}
operations = [NSMutableDictionary dictionary];
//设置关联对象
objc_setAssociatedObject(self, &loadOperationKey, operations, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
return operations;
}
后面几行内容就是取消掉当前operation的下载操作。因为可能是UIImageView的动画图片,所以就去数组中一个个的取消。如果是SDWebImage自定义的对象肯定会实现自定义的取消协议,则转换对象后取消。否则直接将这个object从字典中删除。
至此,取消当前图片下载步骤完毕。
重点二
调用SDWebImageManager,创建下载图片的operation。
- (id )downloadImageWithURL:(NSURL *)url
options:(SDWebImageOptions)options
progress:(SDWebImageDownloaderProgressBlock)progressBlock
completed:(SDWebImageCompletionWithFinishedBlock)completedBlock;
该方法的内部实现是SDWebImage的核心,所有的精华都在这里。
实现中多次使用dispatch_main_sync_safe
和dispatch_main_async_safe
。他们俩分别对应两个宏,一是为防止在主线程执行主线程操作发生死锁;二是避免不必要的开销。dispatch_async不管怎么说都会有一定的开销吧(此处存疑)。
#define dispatch_main_sync_safe(block)\
if ([NSThread isMainThread]) {\
block();\
} else {\
dispatch_sync(dispatch_get_main_queue(), block);\
}
#define dispatch_main_async_safe(block)\
if ([NSThread isMainThread]) {\
block();\
} else {\
dispatch_async(dispatch_get_main_queue(), block);\
}
SDWebImageManager方法downloadImageWithURL
具体步骤
第一步
验证url,如果是字符串转换为NSURL,如果不是NSURL类型,url置为nil。
if ([url isKindOfClass:NSString.class]) {
url = [NSURL URLWithString:(NSString *)url];
}
// Prevents app crashing on argument type error like sending NSNull instead of NSURL
if (![url isKindOfClass:NSURL.class]) {
url = nil;
}
第二步
创建一个SDWebImageCombinedOperation对象,代表一个图片加载任务,但是实际下载图片的事是由另一个Operation来做,该类也实现了SDWebImageOperation协议。因为可能会在block中调用operation,所以先处理处理好循环引用问题。
__block SDWebImageCombinedOperation *operation = [SDWebImageCombinedOperation new];
__weak SDWebImageCombinedOperation *weakOperation = operation;
第三步
BOOL isFailedUrl = NO;
//该步骤可能会出现多线程读取问题,所以添加@synchronized同步锁。
@synchronized (self.failedURLs) {
isFailedUrl = [self.failedURLs containsObject:url];
}
if (url.absoluteString.length == 0 || (!(options & SDWebImageRetryFailed) && isFailedUrl)) {
dispatch_main_sync_safe(^{
NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil];
completedBlock(nil, error, SDImageCacheTypeNone, YES, url);
});
return operation;
}
第四步
将operation加进数组中,需要添加同步锁,保证数组的读写安全。
@synchronized (self.runningOperations) {
[self.runningOperations addObject:operation];
}
第五步
获取该网络图片缓存用的key。
NSString *key = [self cacheKeyForURL:url];
展开这个方法是:
- (NSString *)cacheKeyForURL:(NSURL *)url {
if (self.cacheKeyFilter) {
return self.cacheKeyFilter(url);
}
else {
return [url absoluteString];
}
}
这里如果给manager设置过cacheKeyFilter,则会按照自己的设置返回一个字符串作为key,否则会直接返回url 的绝对路径absoluteString。
第六步
operation.cacheOperation = [self.imageCache queryDiskCacheForKey:key done:^(UIImage *image, SDImageCacheType cacheType) {
这一步是为上面第二步创建的operation对象设置cacheOperation。
- (NSOperation *)queryDiskCacheForKey:(NSString *)key done:(SDWebImageQueryCompletedBlock)doneBlock {
if (!doneBlock) {
return nil;
}
//key不存在,报错
if (!key) {
doneBlock(nil, SDImageCacheTypeNone);
return nil;
}
// First check the in-memory cache...
UIImage *image = [self imageFromMemoryCacheForKey:key];
if (image) {
doneBlock(image, SDImageCacheTypeMemory);
return nil;
}
//缓存中没有,创建任务异步读取磁盘
NSOperation *operation = [NSOperation new];
dispatch_async(self.ioQueue, ^{
if (operation.isCancelled) {
return;
}
@autoreleasepool {
UIImage *diskImage = [self diskImageForKey:key];
//在磁盘中找到图片,并在允许的情况下存缓存
if (diskImage && self.shouldCacheImagesInMemory) {
NSUInteger cost = SDCacheCostForImage(diskImage);
[self.memCache setObject:diskImage forKey:key cost:cost];
}
dispatch_async(dispatch_get_main_queue(), ^{
doneBlock(diskImage, SDImageCacheTypeDisk);
});
}
});
return operation;
}
第七步
在cacheOperation的doneBlock中。如果图片取到了缓存图片,则直接将图片等信息通过completedBlock返回。
从runningOperation中删除步骤二中创建的该operation。
dispatch_main_sync_safe(^{
__strong __typeof(weakOperation) strongOperation = weakOperation;
if (strongOperation && !strongOperation.isCancelled) {
completedBlock(image, nil, cacheType, YES, url);
}
});
@synchronized (self.runningOperations) {
[self.runningOperations removeObject:operation];
}
如果返回的图片为nil,或者需要下载,则通过SDWebImageDownloader
的方法创建下载图片的operation
- (id )downloadImageWithURL:(NSURL *)url
options:(SDWebImageDownloaderOptions)options
progress:(SDWebImageDownloaderProgressBlock)progressBlock
completed:(SDWebImageDownloaderCompletedBlock)completedBlock;
下载过程待会详细分析,这里先分析下载完成后的操作。
情形一:回调返回的error,如果不为空,则返回错误给completedBlock。如果url有问题,则把url添加到failedURLs中。
情形二:如果成功,则
先从failedURLs中删除url,里面不包含也没关系。
如果url对应的图片是url不变,但是图片会变的,则不缓存。
如果图片需要转换,则将图片转换后保存到内存和磁盘中,调用block返回图片。如果不需要转换,则直接保存和回调block。
下载过程解析
在downloader中有一个URLCallbacks的可变字典,每一个url作为key,对应一个数组(数组中是字典对象,字典中保存下载operation的progressBlock和completeBlock),然后判断该url是否是首次下载,如果是,则调用创建operation的block,否则直接返回没有初始化的operation(nil)。
- (void)addProgressCallback:(SDWebImageDownloaderProgressBlock)progressBlock completedBlock:(SDWebImageDownloaderCompletedBlock)completedBlock forURL:(NSURL *)url createCallback:(SDWebImageNoParamsBlock)createCallback {
if (url == nil) {
if (completedBlock != nil) {
completedBlock(nil, nil, nil, NO);
}
return;
}
dispatch_barrier_sync(self.barrierQueue, ^{
BOOL first = NO;
if (!self.URLCallbacks[url]) {
self.URLCallbacks[url] = [NSMutableArray new];
first = YES;
}
// Handle single download of simultaneous download request for the same URL
NSMutableArray *callbacksForURL = self.URLCallbacks[url];
NSMutableDictionary *callbacks = [NSMutableDictionary new];
if (progressBlock) callbacks[kProgressCallbackKey] = [progressBlock copy];
if (completedBlock) callbacks[kCompletedCallbackKey] = [completedBlock copy];
[callbacksForURL addObject:callbacks];
self.URLCallbacks[url] = callbacksForURL;
if (first) {
createCallback();
}
});
}
createCallBack内部创建operation过程:
先创建一个NSMutableURLRequest,需要保证该url不被缓存。过程如下:
NSTimeInterval timeoutInterval = wself.downloadTimeout;
if (timeoutInterval == 0.0) {
timeoutInterval = 15.0;
}
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url cachePolicy:(options & SDWebImageDownloaderUseNSURLCache ? NSURLRequestUseProtocolCachePolicy : NSURLRequestReloadIgnoringLocalCacheData) timeoutInterval:timeoutInterval];
request.HTTPShouldHandleCookies = (options & SDWebImageDownloaderHandleCookies);
request.HTTPShouldUsePipelining = YES;
if (wself.headersFilter) {
request.allHTTPHeaderFields = wself.headersFilter(url, [wself.HTTPHeaders copy]);
}
else {
request.allHTTPHeaderFields = wself.HTTPHeaders;
}
然后创建一个operation(SDWebImageDownloaderOperation
)对象,将其放入downloadQueue中,并判断是否设置过后进先出的执行顺序,默认是先进先出的执行。
SDWebImageDownloaderOperation
SDWebImageDownloaderOperation为自定义的NSOperation,其初始化方法为
- (id)initWithRequest:(NSURLRequest *)request
options:(SDWebImageDownloaderOptions)options
progress:(SDWebImageDownloaderProgressBlock)progressBlock
completed:(SDWebImageDownloaderCompletedBlock)completedBlock
cancelled:(SDWebImageNoParamsBlock)cancelBlock {
if ((self = [super init])) {
_request = request;
_shouldDecompressImages = YES;
_shouldUseCredentialStorage = YES;
_options = options;
_progressBlock = [progressBlock copy];
_completedBlock = [completedBlock copy];
_cancelBlock = [cancelBlock copy];
_executing = NO;
_finished = NO;
_expectedSize = 0;
responseFromCached = YES; // Initially wrong until `connection:willCacheResponse:` is called or not called
}
return self;
}
这里需要重写start()
方法,在start()
方法中创建NSURLSession,并应用起代理方法来更新progressBlock 和 completionHandler。还会在不同的结果时,发送通知。
NSURLSession部分还没理顺,会在后期进行更新