SDWebImage源码解读(五)SDWebImageManager之.H文件
前言
通过分析前面的几个分类:UIView+WebCache,UIImageView+WebCache,UIImageView+HighlightedWebCache,UIButton+WebCache,我们发现这几个都是围绕SDWebImageManager转。所以我们就吧这个manager拉出来遛遛。
.H
(一)SDWebImageOperations
映入眼帘,是SDWebImageOperations这个枚举,前面多次提到过这个下载策略位移枚举,我们就来具体看看每一项的含义,一共13项:
1>.默认情况,当一个url加载失败,会把它加入黑名单,并不再加载,这个选项是让这个黑名单失效,换言之,加载失败,下次继续加载
1 /** 2 * By default, when a URL fail to be downloaded, the URL is blacklisted so the library won't keep trying. 3 * This flag disable this blacklisting. 4 */ 5 SDWebImageRetryFailed = 1 << 0,
2>.默认情况,图片在ui交互期间就会下载,这个选项结果是当UIScrollView处于减速的情况时,延迟加载。
1 /** 2 * By default, image downloads are started during UI interactions, this flags disable this feature, 3 * leading to delayed download on UIScrollView deceleration for instance. 4 */ 5 SDWebImageLowPriority = 1 << 1,
3>.只有内存缓存,没有磁盘缓存
/** * This flag disables on-disk caching */ SDWebImageCacheMemoryOnly = 1 << 2,
4>.默认情况,图片一旦下载完成,立即显示。这个选项的作用是图片在下载的过程中,渐进式的显示。
1 /** 2 * This flag enables progressive download, the image is displayed progressively during download as a browser would do. 3 * By default, the image is only displayed once completely downloaded. 4 */ 5 SDWebImageProgressiveDownload = 1 << 3,
5>.根据图片的变化更新缓存,这里的缓存使用nsurlcache
1 /** 2 * Even if the image is cached, respect the HTTP response cache control, and refresh the image from remote location if needed. 3 * The disk caching will be handled by NSURLCache instead of SDWebImage leading to slight performance degradation. 4 * This option helps deal with images changing behind the same request URL, e.g. Facebook graph api profile pics. 5 * If a cached image is refreshed, the completion block is called once with the cached image and again with the final image. 6 * 7 * Use this flag only if you can't make your URLs static with embedded cache busting parameter. 8 */ 9 SDWebImageRefreshCached = 1 << 4,
6>.iOS 4+,当app进入后台,继续图片下载的操作,如果程序在后台被杀死,则操作取消
1 /** 2 * In iOS 4+, continue the download of the image if the app goes to background. This is achieved by asking the system for 3 * extra time in background to let the request finish. If the background task expires the operation will be cancelled. 4 */ 5 SDWebImageContinueInBackground = 1 << 5,
7>.通过设置NSMutableURLRequest.HTTPShouldHandleCookies = YES,保存cookies到NSHTTPCookieStore
1 /** 2 * Handles cookies stored in NSHTTPCookieStore by setting 3 * NSMutableURLRequest.HTTPShouldHandleCookies = YES; 4 */ 5 SDWebImageHandleCookies = 1 << 6,
8>.允许未被信任的SSL证书,多用于测试目的,生产环境尽量不要用。
1 /** 2 * Enable to allow untrusted SSL certificates. 3 * Useful for testing purposes. Use with caution in production. 4 */ 5 SDWebImageAllowInvalidSSLCertificates = 1 << 7,
9>.高优先级,默认情况,加入队列的图片是顺序下载的,设置高优先级,就可以优先下载。
1 /** 2 * By default, images are loaded in the order in which they were queued. This flag moves them to 3 * the front of the queue. 4 */ 5 SDWebImageHighPriority = 1 << 8,
10>.默认情况,当图片正在下载的时候,占位图已经显示,这个选项设置后,当图片完成下载之后,占位图才显示
1 /** 2 * By default, placeholder images are loaded while the image is loading. This flag will delay the loading 3 * of the placeholder image until after the image has finished loading. 4 */ 5 SDWebImageDelayPlaceholder = 1 << 9,
11>.改变动画图片
1 SDWebImageTransformAnimatedImage = 1 << 10,
12>.默认情况,图片下载完成之后会自动添加到imageView上,设置这个选项之后,图片完成之后不会自动设置,需要手动设置。
1 /** 2 * By default, image is added to the imageView after download. But in some cases, we want to 3 * have the hand before setting the image (apply a filter or add it with cross-fade animation for instance) 4 * Use this flag if you want to manually set the image in the completion when success 5 */ 6 SDWebImageAvoidAutoSetImage = 1 << 11,
13>.默认情况下,下载的图片会按图片的原尺寸进行解压,iOS系统里,这个选项将会受到限制内存的影响而缩小图片比例。但是如果我们设置了SDWebImageProgressiveDownload这个选项,图片缩放设置将会无效。这两个选项不能共存。
1 /** 2 * By default, images are decoded respecting their original size. On iOS, this flag will scale down the 3 * images to a size compatible with the constrained memory of devices. 4 * If `SDWebImageProgressiveDownload` flag is set the scale down is deactivated. 5 */ 6 SDWebImageScaleDownLargeImages = 1 << 12
(二)SDWebImageManagerDelegate
下面我们看到 SDWebImageManagerDelegate 这个协议,它共有两个方法,都是可选的。
1 /** 2 * Controls which image should be downloaded when the image is not found in the cache. 3 * 4 * @param imageManager The current `SDWebImageManager` 5 * @param imageURL The url of the image to be downloaded 6 * 7 * @return Return NO to prevent the downloading of the image on cache misses. If not implemented, YES is implied. 8 */ 9 - (BOOL)imageManager:(nonnull SDWebImageManager *)imageManager shouldDownloadImageForURL:(nullable NSURL *)imageURL;
这个代理方法的作用是:当某个图片没有存在于内存中需要到网上下载的时候,用这个方法控制是否去网上下载。返回NO的时候,不下载。不实现这个代理方法,则默认是去网上下载。
1 /** 2 * Allows to transform the image immediately after it has been downloaded and just before to cache it on disk and memory. 3 * NOTE: This method is called from a global queue in order to not to block the main thread. 4 * 5 * @param imageManager The current `SDWebImageManager` 6 * @param image The image to transform 7 * @param imageURL The url of the image to transform 8 * 9 * @return The transformed image object. 10 */ 11 - (nullable UIImage *)imageManager:(nonnull SDWebImageManager *)imageManager transformDownloadedImage:(nullable UIImage *)image withURL:(nullable NSURL *)imageURL;
这个方法的作用是:当一个图片下载之后,缓存到内存和磁盘之前,立即把它替换掉。为了避免阻塞主线程,这个方法在子线程执行。
(三)属性和方法
1>属性
@property (weak, nonatomic, nullable) id <SDWebImageManagerDelegate> delegate; @property (strong, nonatomic, readonly, nullable) SDImageCache *imageCache; @property (strong, nonatomic, readonly, nullable) SDWebImageDownloader *imageDownloader; @property (nonatomic, copy, nullable) SDWebImageCacheKeyFilterBlock cacheKeyFilter;
这几个属性大家都一目了然,中间两个是只读的,最后一个的意思是,cacheKey过滤block。我们可以在这个block内过滤url,注释里有个example,请看:
[[SDWebImageManager sharedManager] setCacheKeyFilter:^(NSURL *url) {
url = [[NSURL alloc] initWithScheme:url.scheme host:url.host path:url.path];
return [url absoluteString];
}];
2>方法
1 /** 2 * Returns global SDWebImageManager instance. 3 * 4 * @return SDWebImageManager shared instance 5 */ 6 + (nonnull instancetype)sharedManager; 7 8 /** 9 * Allows to specify instance of cache and image downloader used with image manager. 10 * @return new instance of `SDWebImageManager` with specified cache and downloader. 11 */ 12 - (nonnull instancetype)initWithCache:(nonnull SDImageCache *)cache downloader:(nonnull SDWebImageDownloader *)downloader NS_DESIGNATED_INITIALIZER;
1.这是两个初始化方法,第一个是单例方法。第二个是指定初始化方法。根据参数,我们可以知道,初始化方法必须要配合SDImageCache和SDWebImageDownloader使用。
1 - (nullable id <SDWebImageOperation>)loadImageWithURL:(nullable NSURL *)url 2 options:(SDWebImageOptions)options 3 progress:(nullable SDWebImageDownloaderProgressBlock)progressBlock 4 completed:(nullable SDInternalCompletionBlock)completedBlock;
2. 我们看这个比较重要的方法,是UIView+WebCache中的那个方法么,看参数:
@param url 图片url
@param options 这个是文章刚开始咱们说的那个枚举
@param progressBlock 这个是下载进度block,在后台子线程执行
@param completedBlock 这个是下载完成执行的block
1 typedef void(^SDExternalCompletionBlock)(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL); 2 3 typedef void(^SDInternalCompletionBlock)(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL);
看这俩block的定义,看名字我们知道,一个是对外的,一个是内部使用的。他们的参数都基本一致,所表示的意义也都一目了然。
1 - (void)saveImageToCache:(nullable UIImage *)image forURL:(nullable NSURL *)url;
3.把url对应的图片存入缓存。
1 - (void)cachedImageExistsForURL:(nullable NSURL *)url 2 completion:(nullable SDWebImageCheckCacheCompletionBlock)completionBlock;
4.异步检查url对应的图片是否已经被缓存,然后早completionBlock中根据结果进行下一步操作,需要说明的是,block内部的操作是在主线程中进行的。
1 - (void)diskImageExistsForURL:(nullable NSURL *)url 2 completion:(nullable SDWebImageCheckCacheCompletionBlock)completionBlock;
5.和4一样,是检查图片是否缓存在磁盘中
- (nullable NSString *)cacheKeyForURL:(nullable NSURL *)url;
6.根据图片url,返回图片缓存对应的关键字key
1 /** 2 * Cancel all current operations 3 */ 4 - (void)cancelAll; 5 6 /** 7 * Check one or more operations running 8 */ 9 - (BOOL)isRunning;
7.取消所有当前所有操作,检测当前是否有操作正在执行。
.h文件已经解析完毕,接下来我们来解析.m文件。