SDWebImage内部实现过程

  • SDWebImage库的作用:
    通过对UIImageView的类别扩展来实现异步加载替换图片的工作。 主要用到的对象:
    • 1、UIImageView (WebCache)类别,入口封装,实现读取图片完成后的回调
    • 2、SDWebImageManager,对图片进行管理的中转站,记录那些图片正在读取。 向下层读取Cache(调用SDImageCache),或者向网络读取对象(调用SDWebImageDownloader)。
      实现SDImageCache和SDWebImageDownloader的回调。
    • 3、SDImageCache,根据URL的MD5摘要对图片进行存储和读取(实现存在内存中或者存在硬盘上两种实现) 实现图片和内存清理工作。
    • 4、SDWebImageDownloader,根据URL向网络读取数据(实现部分读取和全部读取后再通知回调两种方式)

SDWebImage内部实现过程(新版本在各方法前加上了sd_前缀,以区分UIImageView+AFNetworking中的方法)
  • 1.入口 setImageWithURL:placeholderImage:options:会先把 placeholderImage 显示,然后 SDWebImageManager 根据 URL 开始处理图片。

  • 2.进入 SDWebImageManager-downloadWithURL:delegate:options:userInfo:,交给 SDImageCache 从缓存查找图片是否已经下载 queryDiskCacheForKey:delegate:userInfo:.

  • 3.先从内存图片缓存查找是否有图片,如果内存中已经有图片缓存,SDImageCacheDelegate 回调 imageCache:didFindImage:forKey:userInfo: 到 SDWebImageManager。

  • 4.SDWebImageManagerDelegate 回调 webImageManager:didFinishWithImage:到 UIImageView+WebCache 等前端展示图片。

  • 5.如果内存缓存中没有,生成 NSInvocationOperation 添加到队列开始从硬盘查找图片是否已经缓存。

  • 6.根据 URLKey 在硬盘缓存目录下尝试读取图片文件。这一步是在 NSOperation 进行的操作,所以回主线程进行结果回调 notifyDelegate:。

  • 7.如果上一操作从硬盘读取到了图片,将图片添加到内存缓存中(如果空闲内存过小,会先清空内存缓存)。SDImageCacheDelegate 回调 imageCache:didFindImage:forKey:userInfo:。进而回调展示图片。

  • 8.如果从硬盘缓存目录读取不到图片,说明所有缓存都不存在该图片,需要下载图片,回调 imageCache:didNotFindImageForKey:userInfo:。

  • 9.共享或重新生成一个下载器 SDWebImageDownloader 开始下载图片。

  • 10.图片下载由 NSURLConnection 来做,实现相关 delegate 来判断图片下载中、下载完成和下载失败。

  • 11.connection:didReceiveData:中利用 ImageIO 做了按图片下载进度加载效果。

  • 12.connectionDidFinishLoading:数据下载完成后交给 SDWebImageDecoder 做图片解码处理。

  • 13.图片解码处理在一个 NSOperationQueue 完成,不会拖慢主线程 UI。如果有需要对下载的图片进行二次处理,最好也在这里完成,效率会好很多。

  • 14.在主线程 notifyDelegateOnMainThreadWithInfo: 宣告解码完成,imageDecoder:didFinishDecodingImage:userInfo: 回调给 SDWebImageDownloader。

  • 15.imageDownloader:didFinishWithImage: 回调给 SDWebImageManager 告知图片下载完成。

  • 16.通知所有的 downloadDelegates 下载完成,回调给需要的地方展示图片。

  • 17.将图片保存到 SDImageCache 中,内存缓存和硬盘缓存同时保存。写文件到硬盘也在以单独 NSInvocationOperation 完成,避免拖慢主线程。

  • 18.SDImageCache 在初始化的时候会注册一些消息通知,在内存警告或退到后台的时候清理内存图片缓存,应用结束的时候清理过期图片。

  • 19.SDWI 也提供了 UIButton+WebCache 和 MKAnnotationView+WebCache,方便使用。

  • 20.SDWebImagePrefetcher 可以预先下载图片,方便后续使用。

    从上面流程可以看出,当你调用setImageWithURL:方法的时候,他会自动去给你干这么多事,当你需要在某一具体时刻做事情的时候,你可以覆盖这些方法。比如在下载某个图片的过程中要响应一个事件,就覆盖这个方法:

    覆盖方法,指哪打哪,这个方法是下载imagePath2的时候响应

SDWebImageManager *manager = [SDWebImageManager sharedManager];

    [manager downloadImageWithURL:imagePath2 options:SDWebImageRetryFailed progress:^(NSInteger receivedSize, NSInteger expectedSize) {

        NSLog(@"显示当前进度");

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

        NSLog(@"下载完成");
    }];

当服务器更新了某一张图片资源时,客户端需要重新加载,那么就可以设置SDWebImageOption为SDWebImageRefreshCached;附上全部的SDWebImageOptions:

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.
     */
    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.
     */
    SDWebImageLowPriority = 1 << 1,

    /**
     * This flag disables on-disk caching
     */
    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.
     */
    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.
     */
    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.
     */
    SDWebImageContinueInBackground = 1 << 5,

    /**
     * Handles cookies stored in NSHTTPCookieStore by setting
     * NSMutableURLRequest.HTTPShouldHandleCookies = YES;
     */
    SDWebImageHandleCookies = 1 << 6,

    /**
     * Enable to allow untrusted SSL ceriticates.
     * Useful for testing purposes. Use with caution in production.
     */
    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).
     */
    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.
     */
    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.
     */
    SDWebImageTransformAnimatedImage = 1 << 10,
};

SDWebImage内容补充

这里写图片描述

  • SDWebImage会自动进行内存缓存和磁盘缓存

    • SDWebImage的磁盘缓存, 是按照时间来处理的, 只要缓存数据超过了最大的缓存时间, 就会自动删除
    • SDWebImage默认的磁盘缓存时间是多久?
      • 1周
    • SDWebImage接收到内存警告会如何处理
      • 只要接收到内存警告就会调用 clearMemory 清空内存缓存
    • SDWebImage即将要被终结如何处理
      • 会调用 cleanDisk 方法, 删除过期的文件
    • SDWebImage存储到什么为止
      • caches文件夹下面
      • 新建一个default文件夹用于缓存
    • SDWebImage是如何清空缓存 ?

      • clearMemory
      • 移除NSCache中保存的所有图片对象
    • SDWebImage是如何清除磁盘

      • cleanDisk : 清除过期的
        • 遍历缓存目录, 找到所有过期的文件, 并删除
        • 查看当maxCacheSize的值, 如果删除之后缓存的大小, 还大于maxCacheSize, 那么就会从时间较早的开始继续删除, 直到缓存大小小于maxCacheSize为止
      • clearDisk : 清除所有
        • 直接干掉缓存文件夹
        • 重新创建一个新的文件夹, 作为缓存文件
    • SDWebImage可以直接播放GIF图片

      • 加载GIF图片, 然后取出GIF图片中所有的帧, 并且计算动画时间
      • 根据取出的帧和动画时间生产一张新的可动画的图片
    • SDWebImage它可以判断图片的类型

      • 图片的十六进制数据, 的前8个字节都是一样的, 所以可以同判断十六进制来判断图片的类型
      • PNG
      • JPG

SDWebImage基本使用

  • 01 设置imageView的图片
[cell.imageView sd_setImageWithURL:[NSURL URLWithString:app.icon] placeholderImage:[UIImage imageNamed:@"placehoder"]];
  • 02 设置图片并计算下载进度
 //下载并设置图片
    /*
     第一个参数:要下载图片的url地址
     第二个参数:设置该imageView的占位图片
     第三个参数:传一个枚举值,告诉程序你下载图片的策略是什么
     第一个block块:获取当前图片数据的下载进度
         receivedSize:已经下载完成的数据大小
         expectedSize:该文件的数据总大小
     第二个block块:当图片下载完成之后执行该block中的代码
         image:下载得到的图片数据         error:下载出现的错误信息
         SDImageCacheType:图片的缓存策略(不缓存,内存缓存,沙盒缓存)
         imageURL:下载的图片的url地址
     */
    [cell.imageView sd_setImageWithURL:[NSURL URLWithString:app.icon] placeholderImage:[UIImage imageNamed:@"placehoder"] options:SDWebImageRetryFailed progress:^(NSInteger receivedSize, NSInteger expectedSize) {

        //计算当前图片的下载进度
        NSLog(@"%.2f",1.0 *receivedSize / expectedSize);

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

    }];
  • 03 系统级内存警告如何处理(面试)
    //取消当前正在进行的所有下载操作
    [[SDWebImageManager sharedManager] cancelAll];

    //清除缓存数据(面试)
    //cleanDisk:删除过期的文件数据,计算当前未过期的已经下载的文件数据的大小,如果发现该数据大小大于我们设置的最大缓存数据大小,那么程序内部会按照按文件数据缓存的时间从远到近删除,知道小于最大缓存数据为止。

    //clearMemory:直接删除文件,重新创建新的文件夹
    //[[SDWebImageManager sharedManager].imageCache cleanDisk];
    [[SDWebImageManager sharedManager].imageCache clearMemory];
  • 04 SDWebImage默认的缓存时间是1周
  • 05 如何播放gif图片
 5-1 把用户传入的gif图片->NSData
 5-2 根据该Data创建一个图片数据源(NSData->CFImageSourceRef)
 5-3 计算该数据源中一共有多少帧,把每一帧数据取出来放到图片数组中
 5-4 根据得到的数组+计算的动画时间-》可动画的image
    [UIImage animatedImageWithImages:images duration:duration];
  • 06 如何判断当前图片类型,只判断图片二进制数据的第一个字节
+ (NSString *)sd_contentTypeForImageData:(NSData *)data;
  • 07 内部如何进行缓存处理?使用了NSCache类,使用和NSDictionary类似

  • 08 沙盒缓存图片的命名方式为对该图片的URL进行MD5加密 echo -n "url" |MD5

  • 09 当接收到内存警告之后,内部会自动清理内存缓存

  • 10 图片的下载顺序,默认是先进先出的

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值