源码分析SDWebImage

/*

* This file is part of the SDWebImage package.

* (c) Olivier Poitrey  *

* For the full copyright and license information, please view the LICENSE

* file that was distributed with this source code.

*/

#import "SDWebImageCompat.h"

#import "SDWebImageOperation.h"

#import "SDWebImageDownloader.h"

#import "SDImageCache.h"

typedef NS_OPTIONS(NSUInteger, SDWebImageOptions) {

/**

* By default, when a URL fail to be downloaded, the URL is blacklisted so the library won't keep trying.

* This flag disable this blacklisting.

*/

/**

*

默认情况下,如果一个url在下载的时候失败了,那么这个url会被加入黑名单并且library不会尝试再次下载,这个flag会阻止library把

失败的url加入黑名单(简单来说如果选择了这个flag,那么即使某个url下载失败了,sdwebimage还是会尝试再次下载他.)

*/

SDWebImageRetryFailed = 1 << 0,

/**

* By default, image downloads are started during UI interactions, this flags disable this feature,

* leading to delayed download on UIScrollView deceleration for instance.

*/

/**

*默认情况下,图片会在交互发生的时候下载(例如你滑动tableview的时候),这个flag会禁止这个特性,导致的结果就是在scrollview减速的时候

*才会开始下载(也就是你滑动的时候scrollview不下载,你手从屏幕上移走,scrollview开始减速的时候才会开始下载图片)

*/

SDWebImageLowPriority = 1 << 1,

/**

* This flag disables on-disk caching

*/

/*

*这个flag禁止磁盘缓存,只有内存缓存

*/

SDWebImageCacheMemoryOnly = 1 << 2,

/**

* This flag enables progressive download, the image is displayed progressively during download as a browser would do.

* By default, the image is only displayed once completely downloaded.

*/

/*

*这个flag会在图片下载的时候就显示(就像你用浏览器浏览网页的时候那种图片下载,一截一截的显示(待确认))

*

*/

SDWebImageProgressiveDownload = 1 << 3,

/**

* Even if the image is cached, respect the HTTP response cache control, and refresh the image from remote location if needed.

* The disk caching will be handled by NSURLCache instead of SDWebImage leading to slight performance degradation.

* This option helps deal with images changing behind the same request URL, e.g. Facebook graph api profile pics.

* If a cached image is refreshed, the completion block is called once with the cached image and again with the final image.

*

* Use this flag only if you can't make your URLs static with embeded cache busting parameter.

*/

/*

*这个选项的意思看的不是很懂,大意是即使一个图片缓存了,还是会重新请求.并且缓存侧略依据NSURLCache而不是SDWebImage.

*

*/

SDWebImageRefreshCached = 1 << 4,

/**

* In iOS 4+, continue the download of the image if the app goes to background. This is achieved by asking the system for

* extra time in background to let the request finish. If the background task expires the operation will be cancelled.

*/

/*

*启动后台下载,加入你进入一个页面,有一张图片正在下载这时候你让app进入后台,图片还是会继续下载(这个估计要开backgroundfetch才有用)

*/

SDWebImageContinueInBackground = 1 << 5,

/**

* Handles cookies stored in NSHTTPCookieStore by setting

* NSMutableURLRequest.HTTPShouldHandleCookies = YES;

*/

/*

*可以控制存在NSHTTPCookieStore的cookies.(我没用过,等用过的人过来解释一下)

*/

SDWebImageHandleCookies = 1 << 6,

/**

* Enable to allow untrusted SSL ceriticates.

* Useful for testing purposes. Use with caution in production.

*/

/*

*允许不安全的SSL证书,在正式环境中慎用

*/

SDWebImageAllowInvalidSSLCertificates = 1 << 7,

/**

* By default, image are loaded in the order they were queued. This flag move them to

* the front of the queue and is loaded immediately instead of waiting for the current queue to be loaded (which

* could take a while).

*/

/*

*默认情况下,image在装载的时候是按照他们在队列中的顺序装载的(就是先进先出).这个flag会把他们移动到队列的前端,并且立刻装载

*而不是等到当前队列装载的时候再装载.

*/

SDWebImageHighPriority = 1 << 8,

/**

* By default, placeholder images are loaded while the image is loading. This flag will delay the loading

* of the placeholder image until after the image has finished loading.

*/

/*

*默认情况下,占位图会在图片下载的时候显示.这个flag开启会延迟占位图显示的时间,等到图片下载完成之后才会显示占位图.(等图片显示完了我干嘛还显示占位图?或许是我理解错了?)

*/

SDWebImageDelayPlaceholder = 1 << 9,

/**

* We usually don't call transformDownloadedImage delegate method on animated images,

* as most transformation code would mangle it.

* Use this flag to transform them anyway.

*/

/*

*

是否transform图片(没用过,还要再看,但是据我估计,是否是图片有可能方向不对需要调整方向,例如采用iPhone拍摄的照片如果不纠正方向,

那么图片是向左旋转90度的.可能很多人不知道iPhone的摄像头并不是竖直的,而是向左偏了90度.具体请google.)

*/

SDWebImageTransformAnimatedImage = 1 << 10,

};

typedef void(^SDWebImageCompletionBlock)(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL);

typedef void(^SDWebImageCompletionWithFinishedBlock)(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL);

typedef NSString *(^SDWebImageCacheKeyFilterBlock)(NSURL *url);

@class SDWebImageManager;

@protocol SDWebImageManagerDelegate @optional

/**

* Controls which image should be downloaded when the image is not found in the cache.

*

* @param imageManager The current `SDWebImageManager`

* @param imageURL     The url of the image to be downloaded

*

* @return Return NO to prevent the downloading of the image on cache misses. If not implemented, YES is implied.

*/

/*

*主要作用是当缓存里没有发现某张图片的缓存时,是否选择下载这张图片(默认是yes),可以选择no,那么sdwebimage在缓存中没有找到这张图片的时候不会选择下载

*/

- (BOOL)imageManager:(SDWebImageManager *)imageManager shouldDownloadImageForURL:(NSURL *)imageURL;

/**

* Allows to transform the image immediately after it has been downloaded and just before to cache it on disk and memory.

* NOTE: This method is called from a global queue in order to not to block the main thread.

*

* @param imageManager The current `SDWebImageManager`

* @param image        The image to transform

* @param imageURL     The url of the image to transform

*

* @return The transformed image object.

*/

/**

*在图片下载完成并且还没有加入磁盘缓存或者内存缓存的时候就transform这个图片.这个方法是在异步线程执行的,防治阻塞主线程.

*至于为什么在异步执行很简单,对一张图片纠正方向(也就是transform)是很耗资源的,一张2M大小的图片纠正方向你可以用instrument测试一下耗时.

*很恐怖

*/

- (UIImage *)imageManager:(SDWebImageManager *)imageManager transformDownloadedImage:(UIImage *)image withURL:(NSURL *)imageURL;

@end

/**

* The SDWebImageManager is the class behind the UIImageView+WebCache category and likes.

* It ties the asynchronous downloader (SDWebImageDownloader) with the image cache store (SDImageCache).

* You can use this class directly to benefit from web image downloading with caching in another context than

* a UIView.

*

* Here is a simple example of how to use SDWebImageManager:

*

* @code

SDWebImageManager *manager = [SDWebImageManager sharedManager];

[manager downloadImageWithURL:imageURL

options:0

progress:nil

completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {

if (image) {

// do something with image

}

}];

* @endcode

*/

/*

*

这一段是阐述SDWebImageManager是干嘛的.其实UIImageView+WebCache这个category背后执行操作的就是这个

SDWebImageManager.他会绑定一个下载器也就是SDWebImageDownloader和一个缓存SDImageCache.后面的大

意应该是讲你可以直接使用一个其他上下文环境的SDWebImageManager,而不是仅仅限于一个UIView.

*/

@interface SDWebImageManager : NSObject

@property (weak, nonatomic) id  delegate;

/**

*如同上文所说,一个SDWebImageManager会绑定一个imageCache和一个下载器.

*/

@property (strong, nonatomic, readonly) SDImageCache *imageCache;

@property (strong, nonatomic, readonly) SDWebImageDownloader *imageDownloader;

/**

* The cache filter is a block used each time SDWebImageManager need to convert an URL into a cache key. This can

* be used to remove dynamic part of an image URL.

*

* The following example sets a filter in the application delegate that will remove any query-string from the

* URL before to use it as a cache key:

*

* @code

[[SDWebImageManager sharedManager] setCacheKeyFilter:^(NSURL *url) {

url = [[NSURL alloc] initWithScheme:url.scheme host:url.host path:url.path];

return [url absoluteString];

}];

* @endcode

*/

/*

* 这

个cacheKeyFilter是干嘛的呢?很简单.1他是一个block.2.这个block的作用就是生成一个image的key.因为

sdwebimage的缓存原理你可以当成是一个字典,每一个字典的value就是一张image,那么这个value对应的key是什么呢?就是

cacheKeyFilter根据某个规则对这个图片的url做一些操作生成的.上面的示例就显示了怎么利用这个block把image的url重新组合

生成一个key.以后当sdwebimage检测到你

*/

@property (nonatomic, copy) SDWebImageCacheKeyFilterBlock cacheKeyFilter;

/**

* Returns global SDWebImageManager instance.

*

* @return SDWebImageManager shared instance

*/

/*

*这个不用我解释了吧,生成一个SDWebImagemanager的单例.

*/

+ (SDWebImageManager *)sharedManager;

/**

* Downloads the image at the given URL if not present in cache or return the cached version otherwise.

* 从给定的URL中下载一个之前没有被缓存的Image.

*

* @param url            The URL to the image

* @param options        A mask to specify options to use for this request

* @param progressBlock  A block called while image is downloading

* @param completedBlock A block called when operation has been completed.

*

*   This parameter is required.

*

*   This block has no return value and takes the requested UIImage as first parameter.

*   In case of error the image parameter is nil and the second parameter may contain an NSError.

*

*   The third parameter is an `SDImageCacheType` enum indicating if the image was retrived from the local cache

*   or from the memory cache or from the network.

*

*   The last parameter is set to NO when the SDWebImageProgressiveDownload option is used and the image is

*   downloading. This block is thus called repetidly with a partial image. When image is fully downloaded, the

*   block is called a last time with the full image and the last parameter set to YES.

*

* @return Returns an NSObject conforming to SDWebImageOperation. Should be an instance of SDWebImageDownloaderOperation

*/

/*

* 这个方法主要就是SDWebImage下载图片的方法了.

* 第一个参数是必须要的,就是image的url

* 第二个参数就是我们上面的Options,你可以定制化各种各样的操作.详情参上.

* 第三个参数是一个回调block,用于图片在下载过程中的回调.(英文注释应该是有问题的.)

* 第四个参数是一个下载完成的回调.会在图片下载完成后回调.

* 返回值是一个NSObject类,并且这个NSObject类是conforming一个协议这个协议叫做SDWebImageOperation,这个协议很简单,就是一个cancel掉operation的协议.

*/

- (id )downloadImageWithURL:(NSURL *)url

options:(SDWebImageOptions)options

progress:(SDWebImageDownloaderProgressBlock)progressBlock

completed:(SDWebImageCompletionWithFinishedBlock)completedBlock;

/**

* Saves image to cache for given URL

*

* @param image The image to cache

* @param url   The URL to the image

*

*/

/*

* 将图片存入cache的方法,类似于字典的setValue: forKey:

*/

- (void)saveImageToCache:(UIImage *)image forURL:(NSURL *)url;

/**

* Cancel all current opreations

*/

/*

*取消掉当前所有的下载图片的operation

*/

- (void)cancelAll;

/**

* Check one or more operations running

*/

/*

* check一下是否有一个或者多个operation正在执行(简单来说就是check是否有图片在下载)

*/

- (BOOL)isRunning;

/**

*  Check if image has already been cached

*

*  @param url image url

*

*  @return if the image was already cached

*/

/*

* 通过一个image的url是否已经存在,如果存在返回yes,否则返回no

*/

- (BOOL)cachedImageExistsForURL:(NSURL *)url;

/**

*  Check if image has already been cached on disk only

*

*  @param url image url

*

*  @return if the image was already cached (disk only)

*/

/*

* 检测一个image是否已经被缓存到磁盘(是否存且仅存在disk里).

*/

- (BOOL)diskImageExistsForURL:(NSURL *)url;

/**

*  Async check if image has already been cached

*

*  @param url              image url

*  @param completionBlock  the block to be executed when the check is finished

*

*  @note the completion block is always executed on the main queue

*/

/*

* 如果检测到图片已经被缓存,那么执行回调block.这个block会永远执行在主线程.也就是你可以在这个回调block里更新ui.

*/

- (void)cachedImageExistsForURL:(NSURL *)url

completion:(SDWebImageCheckCacheCompletionBlock)completionBlock;

/**

*  Async check if image has already been cached on disk only

*

*  @param url              image url

*  @param completionBlock  the block to be executed when the check is finished

*

*  @note the completion block is always executed on the main queue

*/

/*

* 如果检测到图片已经被缓存在磁盘(存且仅存在disk),那么执行回调block.这个block会永远执行在主线程.也就是你可以在这个回调block里更新ui.

*/

- (void)diskImageExistsForURL:(NSURL *)url

completion:(SDWebImageCheckCacheCompletionBlock)completionBlock;

/**

*Return the cache key for a given URL

*/

/*

* 通过image的url返回image存在缓存里的key.有人会问了,为什么不直接把图片的url当做image的key来使用呢?而是非要对url做一些处理才能当做key.我的解释是,我也不太清楚.可能为了防止重复吧.

*/

- (NSString *)cacheKeyForURL:(NSURL *)url;

@end

#pragma mark - Deprecated

typedef void(^SDWebImageCompletedBlock)(UIImage *image, NSError *error, SDImageCacheType cacheType) __deprecated_msg("Block type deprecated. Use `SDWebImageCompletionBlock`");

typedef void(^SDWebImageCompletedWithFinishedBlock)(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished) __deprecated_msg("Block type deprecated. Use `SDWebImageCompletionWithFinishedBlock`");

// 已被废弃

@interface SDWebImageManager (Deprecated)

/**

*  Downloads the image at the given URL if not present in cache or return the cached version otherwise.

*

*  @deprecated This method has been deprecated. Use `downloadImageWithURL:options:progress:completed:`

*/

- (id )downloadWithURL:(NSURL *)url

options:(SDWebImageOptions)options

progress:(SDWebImageDownloaderProgressBlock)progressBlock

completed:(SDWebImageCompletedWithFinishedBlock)completedBlock __deprecated_msg("Method deprecated. Use `downloadImageWithURL:options:progress:completed:`");

@end

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 198,932评论 5 466
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,554评论 2 375
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 145,894评论 0 328
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,442评论 1 268
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,347评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 47,899评论 1 275
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,325评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,980评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,196评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,163评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,085评论 1 328
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,826评论 3 316
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,389评论 3 302
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,501评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,753评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,171评论 2 344
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,616评论 2 339

推荐阅读更多精彩内容