iOS开发你需要知道的

SDWebImage原理

2022-03-17  本文已影响0人  喜剧收尾_XWX

SDWebImage

SDWebImage原理

SDWebImageManager核心类介绍

SDWebImageManager是一个单例,SDWebImageManager用于支撑WebCache分类加载图片,连接SDwebImageDownloader异步加载器和SDWebImageCache缓存模块

主要包含

SDWebImageManagerDelegate

- (BOOL)imageManager:(nonnull SDWebImageManager *)imageManager shouldDownloadImageForURL:(nonnull NSURL *)imageURL;
- (BOOL)imageManager:(nonnull SDWebImageManager *)imageManager shouldBlockFailedURL:(nonnull NSURL *)imageURL withError:(nonnull NSError *)error;

SDWebImageManagerDelegate中包含了两个方法

图片加载过程

目前图片加载主要是用到分类,以UIImageView+WebCache为例子加载网络图片主要是调用sd_setImageWithURL方法,而这些方法最终都会调用到SDWebImageManager- (nullable SDWebImageCombinedOperation *)loadImageWithURL:(nullable NSURL *)url options:(SDWebImageOptions)options progress:(nullable SDImageLoaderProgressBlock)progressBlock completed:(nonnull SDInternalCompletionBlock)completedBlock 详细的加载过程如下

  1. 判断传入url的合法性,如果是字符串将其转换成NSURL,如果不存在则将url安置为nil
  2. 判断是否为失败过得URL [self.failedURLs containsObject:url]
  3. 如果URL的字符串长度为0,或者该url请求失败过,且传入的options不是SDWebImageRetryFailed,返回错误 (options & SDWebImageRetryFailed)
  4. 创建SDWebImageCombinedOperation *operation操作,并将其加入到当前运行的所有操作中[self.runningOperations addObject:operation]; > 两个核心概念:queue(队列)、Operation(操作)
  5. 判断options是不是SDWebImageFromLoaderOnly.如果是直接跳转到下载步骤.如果不是根据url拿到缓存的key
  6. 根据拿到的key在SDImageCache中查找缓存
  7. 如果有缓存成功回调,没有缓存跳转到下载步骤
  8. 如果缓存中没有找到,且同事满足以下3中情况则使用 SDImageLoader下载
    * options不是SDWebImageFromCacheOnly
    * 不存在缓存图片或者options为SDWebImageRefreshCached
    * SDWebImageManager中的代理 [self.delegate imageManager:self shouldDownloadImageForURL:url]为yes
  9. 下载报错,将url添加到全局的failedURLs,返回错误
  10. 下载成功,将url从全局的failedURLs中移除,然后对图片进行缓存(内存和磁盘),然后成功返回.图片加载完成.

图片缓存

结构

SDImageCache单例中主包含是SDImageCacheConfigSDMemoryCacheSDDiskCache三个模块

缓存清理时机

清理磁盘的策略

参考链接

参考链接

下载模块 SDwebImageDownloader

该模块主要包含SDWebImageDownloaderConfigSDwebImageDownloader

下载会对调用一下方法

- (nullable SDWebImageDownloadToken *)downloadImageWithURL:(nullable NSURL *)url
                                                   options:(SDWebImageDownloaderOptions)options
                                                   context:(nullable SDWebImageContext *)context
                                                  progress:(nullable SDWebImageDownloaderProgressBlock)progressBlock
                                                 completed:(nullable SDWebImageDownloaderCompletedBlock)completedBlock;

上一篇 下一篇

猜你喜欢

热点阅读