SDWebImage source code analysis

SDWebImage source code analysis 

    Every time you read excellent code, it is a profound study, and every imitation is the beginning of creation!

——QQ 316045346 Welcome to communicate

     SDWebImage is a very popular network image loading library in iOS development. If you observe its source code, you will find that there are many files in it. Although there are many files, the author's code structure and order are not clear. The code structure of SDWebImage can be basically divided into three blocks: application layer category, core function category, tool category and category. The one we use most often is the category of the application layer. For example, the image loading of UIImageView, the image loading of UIButton, etc.

1. Analysis of helper classes and categories

1.NSData+ImageContentType

    This category is a format helper class for image data. It can be used to easily obtain the image format of image data. The commonly used image formats are enumerated as follows:

typedef NS_ENUM(NSInteger, SDImageFormat) {
    SDImageFormatUndefined = -1, //未知格式
    SDImageFormatJPEG = 0,   //jpeg
    SDImageFormatPNG,   //png
    SDImageFormatGIF,   //gif
    SDImageFormatTIFF,  //tiff
    SDImageFormatWebP,  //webp
    SDImageFormatHEIC   //heic
};

The principle is to analyze the first byte code of the image data. Image data of different formats will have a part of the data block at the beginning to indicate the image information, through which the specific format of the image can be obtained. Only two methods are provided in this category:

//获取图像数据格式
+ (SDImageFormat)sd_imageFormatForImageData:(nullable NSData *)data;
//将SDImageFormat转换成CFStringRef
+ (nonnull CFStringRef)sd_UTTypeFromSDImageFormat:(SDImageFormat)format;

2、SDWebImageFrame

    This class is the image frame class encapsulated in SDWebImage, which is mainly used to create animation images.

//当前帧图像
@property (nonatomic, strong, readonly, nonnull) UIImage *image;
//时间
@property (nonatomic, readonly, assign) NSTimeInterval duration;
//初始化方法
+ (instancetype _Nonnull)frameWithImage:(UIImage * _Nonnull)image duration:(NSTimeInterval)duration;

3. Encoding and decoding of UIImage

    A protocol is defined in SDWebImageCoder, which stipulates methods to decode and encode image data. The main implementations of this protocol are SDWebImageIOCoder and SDWebImageGIFCoder.

//数据是否可以进行解码 除了webp类型的 其他类型的图像都可以解码
- (BOOL)canDecodeFromData:(nullable NSData *)data;
//进行图片数据解码
- (nullable UIImage *)decodedImageWithData:(nullable NSData *)data;
//进行增量解码
- (nullable UIImage *)decompressedImageWithImage:(nullable UIImage *)image
                                            data:(NSData * _Nullable * _Nonnull)data
                                         options:(nullable NSDictionary<NSString*, NSObject*>*)optionsDict;
//获取此类型图像是否可以编码
- (BOOL)canEncodeToFormat:(SDImageFormat)format;
//将图片编码为数据
- (nullable NSData *)encodedDataWithImage:(nullable UIImage *)image format:(SDImageFormat)format;
//获取此图像数据是否可以增量解码
- (BOOL)canIncrementallyDecodeFromData:(nullable NSData *)data;
//进行增量解码
- (nullable UIImage *)incrementallyDecodedImageWithData:(nullable NSData *)data finished:(BOOL)finished;

4. Image data preload

    The SDWebImagePrefetcher class provides the preloading function of image data. This class can be used when optimizing the user experience and preloading some normal images.

@interface SDWebImagePrefetcher : NSObject
//管理中心
@property (strong, nonatomic, readonly, nonnull) SDWebImageManager *manager;
//设置最大的同时下载数
@property (nonatomic, assign) NSUInteger maxConcurrentDownloads;
//配置 枚举 设置优先级等
@property (nonatomic, assign) SDWebImageOptions options;
//单例对象
+ (nonnull instancetype)sharedImagePrefetcher;
//构造方法
- (nonnull instancetype)initWithImageManager:(nonnull SDWebImageManager *)manager NS_DESIGNATED_INITIALIZER;
//进行预下载
- (void)prefetchURLs:(nullable NSArray<NSURL *> *)urls;
- (void)prefetchURLs:(nullable NSArray<NSURL *> *)urls
            progress:(nullable SDWebImagePrefetcherProgressBlock)progressBlock
           completed:(nullable SDWebImagePrefetcherCompletionBlock)completionBlock;
//取消预下载行为
- (void)cancelPrefetching;

SDWebImagePrefetcher also provides a proxy to monitor the pre-download process, as follows:

//当一张图片被下载完后调用
- (void)imagePrefetcher:(nonnull SDWebImagePrefetcher *)imagePrefetcher didPrefetchURL:(nullable NSURL *)imageURL finishedCount:(NSUInteger)finishedCount totalCount:(NSUInteger)totalCount;
//与下载任务全部结束后调用
- (void)imagePrefetcher:(nonnull SDWebImagePrefetcher *)imagePrefetcher didFinishWithTotalCount:(NSUInteger)totalCount skippedCount:(NSUInteger)skippedCount;

2. Core functions

    The core function class structure of SDWebImage is shown in the following figure:

1. Cache management class SDImageCache

    The SDImageCache class is responsible for the cache of all network image data, which is logically divided into two levels of cache, memory cache and hard disk cache. Developers can use the singleton method to obtain the default SDImageCache instance, or use a special Name value to create a cache instance. Common functions are listed as follows:

//缓存图片到内存和磁盘
- (void)storeImage:(nullable UIImage *)image
            forKey:(nullable NSString *)key
        completion:(nullable SDWebImageNoParamsBlock)completionBlock;
//缓存图片到磁盘
- (void)storeImage:(nullable UIImage *)image
            forKey:(nullable NSString *)key
            toDisk:(BOOL)toDisk
        completion:(nullable SDWebImageNoParamsBlock)completionBlock;
- (void)storeImage:(nullable UIImage *)image
         imageData:(nullable NSData *)imageData
            forKey:(nullable NSString *)key
            toDisk:(BOOL)toDisk
        completion:(nullable SDWebImageNoParamsBlock)completionBlock;
- (void)storeImageDataToDisk:(nullable NSData *)imageData forKey:(nullable NSString *)key;
//异步检查磁盘缓存是否存在
- (void)diskImageExistsWithKey:(nullable NSString *)key completion:(nullable SDWebImageCheckCacheCompletionBlock)completionBlock;
//检查内存缓存是否存在
- (nullable UIImage *)imageFromMemoryCacheForKey:(nullable NSString *)key;
//获取磁盘缓存数据
- (nullable UIImage *)imageFromDiskCacheForKey:(nullable NSString *)key;
//获取内存和磁盘缓存数据
- (nullable UIImage *)imageFromCacheForKey:(nullable NSString *)key;
//异步删除缓存
- (void)removeImageForKey:(nullable NSString *)key withCompletion:(nullable SDWebImageNoParamsBlock)completion;
- (void)removeImageForKey:(nullable NSString *)key fromDisk:(BOOL)fromDisk withCompletion:(nullable SDWebImageNoParamsBlock)completion;
//清除所有内存缓存
- (void)clearMemory;
//删除所有过期数据
- (void)deleteOldFilesWithCompletionBlock:(nullable SDWebImageNoParamsBlock)completionBlock;
//获取磁盘缓存大小
- (NSUInteger)getSize;
//获取磁盘缓存图片数
- (NSUInteger)getDiskCount;

SDImageCacheConfig is used to configure the cache as follows:

//是否允许缓存到内存
@property (assign, nonatomic) BOOL shouldCacheImagesInMemory;
//缓存生命
@property (assign, nonatomic) NSInteger maxCacheAge;
//最大缓存容量
@property (assign, nonatomic) NSUInteger maxCacheSize;

2. Downloader SDWebImageDownloader

    SDWebImageDownloader provides support and management for image download, which can configure the maximum number of simultaneous downloads, download timeout, etc.:

//同时最大下载数量
@property (assign, nonatomic) NSInteger maxConcurrentDownloads;
//当前正在下载的任务数量
@property (readonly, nonatomic) NSUInteger currentDownloadCount;
//设置超时时间
@property (assign, nonatomic) NSTimeInterval downloadTimeout;
//证书
@property (strong, nonatomic, nullable) NSURLCredential *urlCredential;
//用户名
@property (strong, nonatomic, nullable) NSString *username;
//密码
@property (strong, nonatomic, nullable) NSString *password;
//设置请求头
- (void)setValue:(nullable NSString *)value forHTTPHeaderField:(nullable NSString *)field;
//获取请求头
- (nullable NSString *)valueForHTTPHeaderField:(nullable NSString *)field;
//开始下载任务
- (nullable SDWebImageDownloadToken *)downloadImageWithURL:(nullable NSURL *)url
                                                   options:(SDWebImageDownloaderOptions)options
                                                  progress:(nullable SDWebImageDownloaderProgressBlock)progressBlock
                                                 completed:(nullable SDWebImageDownloaderCompletedBlock)completedBlock;
//取消下载任务
- (void)cancel:(nullable SDWebImageDownloadToken *)token;
//取消所有下载任务
- (void)cancelAllDownloads;

3. Application categories

1.UIButton+WebCache

    This category is used to set a web image for the button.

//当前状态的图片URL
- (nullable NSURL *)sd_currentImageURL;
//获取指定状态的图片URL
- (nullable NSURL *)sd_imageURLForState:(UIControlState)state;
//为某个状态设置网络图片
- (void)sd_setImageWithURL:(nullable NSURL *)url
                  forState:(UIControlState)state;
- (void)sd_setImageWithURL:(nullable NSURL *)url
                  forState:(UIControlState)state
          placeholderImage:(nullable UIImage *)placeholder;
- (void)sd_setImageWithURL:(nullable NSURL *)url
                  forState:(UIControlState)state
          placeholderImage:(nullable UIImage *)placeholder
                   options:(SDWebImageOptions)options;
- (void)sd_setImageWithURL:(nullable NSURL *)url
                  forState:(UIControlState)state
                 completed:(nullable SDExternalCompletionBlock)completedBlock;
- (void)sd_setImageWithURL:(nullable NSURL *)url
                  forState:(UIControlState)state
          placeholderImage:(nullable UIImage *)placeholder
                 completed:(nullable SDExternalCompletionBlock)completedBlock;
- (void)sd_setImageWithURL:(nullable NSURL *)url
                  forState:(UIControlState)state
          placeholderImage:(nullable UIImage *)placeholder
                   options:(SDWebImageOptions)options
                 completed:(nullable SDExternalCompletionBlock)completedBlock;
//下面这些方法设置按钮的背景图
- (nullable NSURL *)sd_currentBackgroundImageURL;
- (nullable NSURL *)sd_backgroundImageURLForState:(UIControlState)state;
- (void)sd_setBackgroundImageWithURL:(nullable NSURL *)url
                            forState:(UIControlState)state;
- (void)sd_setBackgroundImageWithURL:(nullable NSURL *)url
                            forState:(UIControlState)state
                    placeholderImage:(nullable UIImage *)placeholder;
- (void)sd_setBackgroundImageWithURL:(nullable NSURL *)url
                            forState:(UIControlState)state
                    placeholderImage:(nullable UIImage *)placeholder
                             options:(SDWebImageOptions)options;
- (void)sd_setBackgroundImageWithURL:(nullable NSURL *)url
                            forState:(UIControlState)state
                           completed:(nullable SDExternalCompletionBlock)completedBlock;
- (void)sd_setBackgroundImageWithURL:(nullable NSURL *)url
                            forState:(UIControlState)state
                    placeholderImage:(nullable UIImage *)placeholder
                           completed:(nullable SDExternalCompletionBlock)completedBlock;
- (void)sd_setBackgroundImageWithURL:(nullable NSURL *)url
                            forState:(UIControlState)state
                    placeholderImage:(nullable UIImage *)placeholder
                             options:(SDWebImageOptions)options
                           completed:(nullable SDExternalCompletionBlock)completedBlock;
//取消图片下载
- (void)sd_cancelImageLoadForState:(UIControlState)state;
- (void)sd_cancelBackgroundImageLoadForState:(UIControlState)state;

2.UIImageView+WebCache与UIImageView+HighlightedWebCache

    The functions of these two categories are to set the picture of the UIImageView instance, respectively setting the picture in the normal state and the picture in the highlighted state. Only the methods in UIImageView+WebCache are as follows:

//设置网络图片
- (void)sd_setImageWithURL:(nullable NSURL *)url;
- (void)sd_setImageWithURL:(nullable NSURL *)url
          placeholderImage:(nullable UIImage *)placeholder;
- (void)sd_setImageWithURL:(nullable NSURL *)url
          placeholderImage:(nullable UIImage *)placeholder
                   options:(SDWebImageOptions)options;
- (void)sd_setImageWithURL:(nullable NSURL *)url
                 completed:(nullable SDExternalCompletionBlock)completedBlock;
- (void)sd_setImageWithURL:(nullable NSURL *)url
          placeholderImage:(nullable UIImage *)placeholder
                 completed:(nullable SDExternalCompletionBlock)completedBlock;
- (void)sd_setImageWithURL:(nullable NSURL *)url
          placeholderImage:(nullable UIImage *)placeholder
                   options:(SDWebImageOptions)options
                 completed:(nullable SDExternalCompletionBlock)completedBlock;
- (void)sd_setImageWithURL:(nullable NSURL *)url
          placeholderImage:(nullable UIImage *)placeholder
                   options:(SDWebImageOptions)options
                  progress:(nullable SDWebImageDownloaderProgressBlock)progressBlock
                 completed:(nullable SDExternalCompletionBlock)completedBlock;
- (void)sd_setImageWithPreviousCachedImageWithURL:(nullable NSURL *)url
                                 placeholderImage:(nullable UIImage *)placeholder
                                          options:(SDWebImageOptions)options
                                         progress:(nullable SDWebImageDownloaderProgressBlock)progressBlock
                                        completed:(nullable SDExternalCompletionBlock)completedBlock;
//对一组url进行下载并以动画方式显示
- (void)sd_setAnimationImagesWithURLs:(nonnull NSArray<NSURL *> *)arrayOfURLs;
//取消当前图片下载
- (void)sd_cancelCurrentAnimationImagesLoad;

Regarding SDWebImageOptions, it is a configuration enum:

typedef NS_OPTIONS(NSUInteger, SDWebImageOptions) {
    //配置这个参数下载失败的url将会重试下载
    SDWebImageRetryFailed = 1 << 0,
    //低优先级
    SDWebImageLowPriority = 1 << 1,
    //仅仅进行内存缓存
    SDWebImageCacheMemoryOnly = 1 << 2,
    //进行分步下载
    SDWebImageProgressiveDownload = 1 << 3,
    //刷新缓存
    SDWebImageRefreshCached = 1 << 4,
    //支持后台
    SDWebImageContinueInBackground = 1 << 5,
    //保持cookie
    SDWebImageHandleCookies = 1 << 6,
    //允许证书
    SDWebImageAllowInvalidSSLCertificates = 1 << 7,
    //高优先级 
    SDWebImageHighPriority = 1 << 8,
    //配置此参数 当图片加载结束后才会显示placeholder
    SDWebImageDelayPlaceholder = 1 << 9,
    //执行图片变换
    SDWebImageTransformAnimatedImage = 1 << 10,
    SDWebImageScaleDownLargeImages = 1 << 12
};

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325458761&siteId=291194637