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;