前言:YYWebImage是YYKit系列中图片请求的框架。作者号称是可以替代SDWebImage框架。至于优秀的SDWebImage的框架在iOS中的地位想必你一定是知道的。再开始学习之前先奉上YYWebImage
框架的地址。当然你也可以先看看YYWebImage
缓存框架的解析
本文准备从YYWebImageDemo中一个网络请求开始,为了更好的解析这个请求的过程。我们先将Demo中YYWebImageExample类请求url数组设置为单个
NSArray *links = @[
@"https://s-media-cache-ak0.pinimg.com/1200x/2e/0c/c5/2e0cc5d86e7b7cd42af225c29f21c37f.jpg"];
下面是这次请求的方法:
[_webImageView yy_setImageWithURL:url
placeholder:nil
options:YYWebImageOptionProgressiveBlur | YYWebImageOptionShowNetworkActivity | YYWebImageOptionSetImageWithFadeAnimation
progress:^(NSInteger receivedSize, NSInteger expectedSize) {
if (expectedSize > 0 && receivedSize > 0) {
CGFloat progress = (CGFloat)receivedSize / expectedSize;
progress = progress < 0 ? 0 : progress > 1 ? 1 : progress;
if (_self.progressLayer.hidden) _self.progressLayer.hidden = NO;
_self.progressLayer.strokeEnd = progress;
}
}
transform:nil
completion:^(UIImage *image, NSURL *url, YYWebImageFromType from, YYWebImageStage stage, NSError *error) {
if (stage == YYWebImageStageFinished) {
_self.progressLayer.hidden = YES;
[_self.indicator stopAnimating];
_self.indicator.hidden = YES;
if (!image) _self.label.hidden = NO;
}
}];
我们先针对上面的请求方法看看相关的参数,如果你使用过SDWebImage
,那这些参数你理解起来应该会比较容易。你最应该注意的是options枚举,因为它在整个流程的地方十分重要(作者给的备注英语通俗易懂,就再不做画蛇添足的翻译了):
本次网络请求主要分为下面三个方面:
1.数据请求阶段前根据option类型的操作。
这个阶段主要的操作就是根据option类型来决定是否直接从内存里面取图像。如果不从内存里面拿,是否需要先暂时显示placeholder。这都是option来决定的。我们现在要做的是跑通一个流程。Here we go!!!下面的代码请结合流程一起看。
- (void)yy_setImageWithURL:(NSURL *)imageURL
placeholder:(UIImage *)placeholder
options:(YYWebImageOptions)options
manager:(YYWebImageManager *)manager
progress:(YYWebImageProgressBlock)progress
transform:(YYWebImageTransformBlock)transform
completion:(YYWebImageCompletionBlock)completion {
if ([imageURL isKindOfClass:[NSString class]]) imageURL = [NSURL URLWithString:(id)imageURL];
manager = manager ? manager : [YYWebImageManager sharedManager];
//runtime 取value
_YYWebImageSetter *setter = objc_getAssociatedObject(self, &_YYWebImageSetterKey);
if (!setter) {
setter = [_YYWebImageSetter new];
objc_setAssociatedObject(self, &_YYWebImageSetterKey, setter, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
int32_t sentinel = [setter cancelWithNewURL:imageURL];
//回到主线程
_yy_dispatch_sync_on_main_queue(^{
//如果option有YYWebImageOptionSetImageWithFadeAnimation且没有YYWebImageOptionAvoidSetImage类型
if ((options & YYWebImageOptionSetImageWithFadeAnimation) &&
!(options & YYWebImageOptionAvoidSetImage)) {
if (!self.highlighted) {
//移除动画
[self.layer removeAnimationForKey:_YYWebImageFadeAnimationKey];
}
}
if (!imageURL) {//当imageURL为空
//options没有YYWebImageOptionIgnorePlaceHolder类型则直接把placeholder赋给image
if (!(options & YYWebImageOptionIgnorePlaceHolder)) {
self.image = placeholder;
}
return;
}
// get the image from memory as quickly as possible
UIImage *imageFromMemory = nil;
//如果options 没有YYWebImageOptionUseNSURLCache,YYWebImageOptionRefreshImageCache类型
if (manager.cache &&
!(options & YYWebImageOptionUseNSURLCache) &&
!(options & YYWebImageOptionRefreshImageCache)) {
//根据key去YYCache里面取UIImage
imageFromMemory = [manager.cache getImageForKey:[manager cacheKeyForURL:imageURL] withType:YYImageCacheTypeMemory];
}
if (imageFromMemory) {
//如果options 没有YYWebImageOptionAvoidSetImage类型
if (!(options & YYWebImageOptionAvoidSetImage)) {
self.image = imageFromMemory;
}
if(completion) completion(imageFromMemory, imageURL, YYWebImageFromMemoryCacheFast, YYWebImageStageFinished, nil);
return;
}
//如果options 没有YYWebImageOptionUseNSURLCache
if (!(options & YYWebImageOptionIgnorePlaceHolder)) {
self.image = placeholder;
}
//============上面是文中数据请求阶段前根据option类型的操作====================================
//因为为了避免下载大尺寸文件或者图片内存爆掉,所以NSURLConnection会把文件或图片分成多段回调。下面就是拿到总expectedSize和每次接收到的receivedSize的block声明
__weak typeof(self) _self = self;
dispatch_async([_YYWebImageSetter setterQueue], ^{
YYWebImageProgressBlock _progress = nil;
if (progress) _progress = ^(NSInteger receivedSize, NSInteger expectedSize) {
dispatch_async(dispatch_get_main_queue(), ^{
progress(receivedSize, expectedSize);
});
};
__block int32_t newSentinel = 0;
__block __weak typeof(setter) weakSetter = nil;
//====================================_completion==================================
// 完成的回调声明
YYWebImageCompletionBlock _completion = ^(UIImage *image, NSURL *url, YYWebImageFromType from, YYWebImageStage stage, NSError *error) {
__strong typeof(_self) self = _self;
BOOL setImage = (stage == YYWebImageStageFinished || stage == YYWebImageStageProgress) && image && !(options & YYWebImageOptionAvoidSetImage);
dispatch_async(dispatch_get_main_queue(), ^{
BOOL sentinelChanged = weakSetter && weakSetter.sentinel != newSentinel;
if (setImage && self && !sentinelChanged) {
BOOL showFade = ((options & YYWebImageOptionSetImageWithFadeAnimation) && !self.highlighted);
if (showFade) {
CATransition *transition = [CATransition animation];
transition.duration = stage == YYWebImageStageFinished ? _YYWebImageFadeTime : _YYWebImageProgressiveFadeTime;
transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
transition.type = kCATransitionFade;
[self.layer addAnimation:transition forKey:_YYWebImageFadeAnimationKey];
}
self.image = image;
}
if (completion) {
if (sentinelChanged) {
completion(nil, url, YYWebImageFromNone, YYWebImageStageCancelled, nil);
} else {
completion(image, url, from, stage, error);
}
}
});
};
//====================================_completion==================================
//将相关参数和声明的block传过去
newSentinel = [setter setOperationWithSentinel:sentinel url:imageURL options:options manager:manager progress:_progress transform:transform completion:_completion];
weakSetter = setter;
});
});
}
2.加入队列数据请求阶段
这部分代码跳转太多,便不贴相关代码了。你运行代码应该能获取下图相关的流程。
3.NSURLConnection回调的处理
// 在构建connection会被响应。如果这个connection需要根据NSURLCredentialStorage中的权限进行构建,那么就返回YES
// 默认是YES,想要修改,需要用户自己指定self.shouldUseCredentialStorage值
- (BOOL)connectionShouldUseCredentialStorage:(NSURLConnection *)connection
//客户端开始认证挑战(Authentication Challenge)
- (void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
//返回相应头的信息。重要的有statusCode,expectedContentLength。回调给size,数据接收的开始阶段。
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
//文件或者图片分割成多份回调
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
//文件下载完毕后的回调
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
//下载失败,失败回调
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
类
流程跑完了,我们现在来看下类图:
YYWebImage使用YYImageCache作缓存(YYCache上层),YYImage做解码相关工作。利用Category分类做提供接口。而
_YYWebImageSetter
是一个私有类,为categories提供接口,值得一提的是它使用
OSAtomicIncrement32
来原子操作级别地递增_sentinel。下面我们主要来看看
YYWebImageManager
,
YYWebImageOperation
。
YYWebImageManager
YYWebImageManager
是YYWebImage的管理类,主要提供了下面管理:
1.图片操作的枚举YYWebImageOptions
2.图片的来源的枚举YYWebImageFromType
3.请取图片状态的枚举YYWebImageStage
4.进度的回调block YYWebImageProgressBlock
5.对图片附加的操作block YYWebImageTransformBlock
6.请求图片完成的block YYWebImageCompletionBlock
YYWebImageOperation
YYWebImageOperation
是NSOperation
的子类,是对一个请求任务的包装来从URL获取图片。它的属性executing
,finished
,cancelled
,started
控制着任务的状态。通过把任务添加到队列,或者手动调用start
方法执行。当一个任务开始:
1.从磁盘里面请求图片,如果存在。返回并completion block回调。
2.开始URL connection请求图片,如果设置了YYWebImageProgressBlock,则返回每一段的Progress
3.如果设置了YYWebImageTransformBlock,则依据block 处理图片
4.把图片存入磁盘。返回并completion block回调。