UIImageView+WebCache
主要功能是给UIImageView添加的一些便利操作,也就是下载、缓存、显示3大部分的显示部分
1、获取获取设置的下载url,
知识点;使用runtime、地址作为唯一key
static char imageURLKey;
- (NSURL *)sd_imageURL {
return objc_getAssociatedObject(self, &imageURLKey);
}
2、设置下载图片的URL,各种组合的便利方法
知识点:
2.1、开始新下载时取消上一次的操作,这是设计一个库时应该考虑的避免意外的错误已经节省资源
2.2、使用runtime保存操作的url
2.3、options不包含SDWebImageDelayPlaceholder才设置placeHolder
2.4、将UI操作放在主线程,并抽成一个宏
#define dispatch_main_async_safe(block)\
if ([NSThread isMainThread]) {\
block();\
} else {\
dispatch_async(dispatch_get_main_queue(), block);\
}
2.5、调用SDWebImageManager的download方法
2.6、持有下载的操作operation以及删除时取消操作
- (void)sd_setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options progress:(SDWebImageDownloaderProgressBlock)progressBlock completed:(SDWebImageCompletionBlock)completedBlock {
// 取消当前下载,从新设置内容
[self sd_cancelCurrentImageLoad];
objc_setAssociatedObject(self, &imageURLKey, url, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
if (!(options & SDWebImageDelayPlaceholder)) {
dispatch_main_async_safe(^{
self.image = placeholder;
});
}
if (url) {
// check if activityView is enabled or not
if ([self showActivityIndicatorView]) {
[self addActivityIndicator];
}
__weak __typeof(self)wself = self;
id <SDWebImageOperation> operation = [SDWebImageManager.sharedManager downloadImageWithURL:url options:options progress:progressBlock completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
[wself removeActivityIndicator];
if (!wself) return;
dispatch_main_sync_safe(^{
if (!wself) return;
if (image && (options & SDWebImageAvoidAutoSetImage) && completedBlock)
{
completedBlock(image, error, cacheType, url);
return;
}
else if (image) {
wself.image = image;
[wself setNeedsLayout];
} else {
if ((options & SDWebImageDelayPlaceholder)) {
wself.image = placeholder;
[wself setNeedsLayout];
}
}
if (completedBlock && finished) {
completedBlock(image, error, cacheType, url);
}
});
}];
[self sd_setImageLoadOperation:operation forKey:@"UIImageViewImageLoad"];
} else {
dispatch_main_async_safe(^{
[self removeActivityIndicator];
if (completedBlock) {
NSError *error = [NSError errorWithDomain:SDWebImageErrorDomain code:-1 userInfo:@{NSLocalizedDescriptionKey : @"Trying to load a nil url"}];
completedBlock(nil, error, SDImageCacheTypeNone, url);
}
});
}
}
3、设置下载动画组的图片下载地址
如果加载的是一个动画组的图片,则遍历所有url进行下载,把所有一个组的操作放入一个数组进行持有,下载好的图片则每下载一个就放入组里开始动画
- (void)sd_setAnimationImagesWithURLs:(NSArray *)arrayOfURLs;
4、设置图片加载中的Indicator
/**
* Show activity UIActivityIndicatorView
*/
- (void)setShowActivityIndicatorView:(BOOL)show;
/**
* set desired UIActivityIndicatorViewStyle
*
* @param style The style of the UIActivityIndicatorView
*/
- (void)setIndicatorStyle:(UIActivityIndicatorViewStyle)style;
5、取消当前下载中的图片,主要场景为离开当前页面,不用再继续下载
/**
* Cancel the current download
*/
- (void)sd_cancelCurrentImageLoad;
- (void)sd_cancelCurrentAnimationImagesLoad;