美文网首页
SDWebImage内部实现过程

SDWebImage内部实现过程

作者: 温水煮青蛙a | 来源:发表于2018-10-13 09:20 被阅读0次
    没有占位图 只加载网络图片
    [imageView sd_setImageWithURL:[NSURL URLWithString:@"http://d.hiphotos.baidu.com/image/pic/item/0ff41bd5ad6eddc4f263b0fc3adbb6fd52663334.jpg"]];
    加载网络图片完成之前  先显示占位图
        [imageView sd_setImageWithURL:[NSURL URLWithString:@"http://d.hiphotos.baidu.com/image/pic/item/0ff41bd5ad6eddc4f263b0fc3adbb6fd52663334.jpg"] placeholderImage:[UIImage imageNamed:@"占位图"]];
        
        [imageView sd_setImageWithURL:[NSURL URLWithString:@"http://d.hiphotos.baidu.com/image/pic/item/0ff41bd5ad6eddc4f263b0fc3adbb6fd52663334.jpg"] placeholderImage:nil options:0];
        
    //用block 可以在图片加载完成之后做些事情
        [imageView sd_setImageWithURL:[NSURL URLWithString:@"http://d.hiphotos.baidu.com/image/pic/item/0ff41bd5ad6eddc4f263b0fc3adbb6fd52663334.jpg"] placeholderImage:nil options:(SDWebImageRetryFailed) completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
            
        }];
        
    //用block 可以在图片加载完成之后做些事情  返回下载进度
        [imageView sd_setImageWithURL:[NSURL URLWithString:@"http://img.hao123.com/data/1_0c668007a70e09b0636bec3b3b0588a9_510"] placeholderImage:nil options:(SDWebImageRetryFailed) progress:^(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL) {
            NSLog(@"下载进度==%f", 1.0*receivedSize/expectedSize);
        } completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
            [self clear];
        }];
    
    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 after the download finished, only cache in memory
    这个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 embedded 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.
    启动后台下载,加入你进入一个页面,有一张图片正在下载这时候你让app进入后台,图片还是会继续下载(这个估计要开backgroundfetch才有用)
         */
        SDWebImageContinueInBackground = 1 << 5,
    
        /**
         * Handles cookies stored in NSHTTPCookieStore by setting
         * NSMutableURLRequest.HTTPShouldHandleCookies = YES;
         */
        SDWebImageHandleCookies = 1 << 6,
    
        /**
         * Enable to allow untrusted SSL certificates.
         * Useful for testing purposes. Use with caution in production.
    允许不安全的SSL证书,在正式环境中慎用
         */
        SDWebImageAllowInvalidSSLCertificates = 1 << 7,
    
        /**
         * By default, images are loaded in the order in which they were queued. This flag moves them to
         * the front of the queue.
    默认情况下,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.
         */
        SDWebImageTransformAnimatedImage = 1 << 10,
        
        /**
         * By default, image is added to the imageView after download. But in some cases, we want to
         * have the hand before setting the image (apply a filter or add it with cross-fade animation for instance)
         * Use this flag if you want to manually set the image in the completion when success
         */
        SDWebImageAvoidAutoSetImage = 1 << 11,
        
        /**
         * By default, images are decoded respecting their original size. On iOS, this flag will scale down the
         * images to a size compatible with the constrained memory of devices.
         * If `SDWebImageProgressiveDownload` flag is set the scale down is deactivated.
         */
        SDWebImageScaleDownLargeImages = 1 << 12,
        
        /**
         * By default, we do not query disk data when the image is cached in memory. This mask can force to query disk data at the same time.
         * This flag is recommend to be used with `SDWebImageQueryDiskSync` to ensure the image is loaded in the same runloop.
         */
        SDWebImageQueryDataWhenInMemory = 1 << 13,
        
        /**
         * By default, we query the memory cache synchronously, disk cache asynchronously. This mask can force to query disk cache synchronously to ensure that image is loaded in the same runloop.
         * This flag can avoid flashing during cell reuse if you disable memory cache or in some other cases.
         */
        SDWebImageQueryDiskSync = 1 << 14,
        
        /**
         * By default, when the cache missed, the image is download from the network. This flag can prevent network to load from cache only.
         */
        SDWebImageFromCacheOnly = 1 << 15,
        /**
         * By default, when you use `SDWebImageTransition` to do some view transition after the image load finished, this transition is only applied for image download from the network. This mask can force to apply view transition for memory and disk cache as well.
         */
        SDWebImageForceTransition = 1 << 16
    };
    

    SDWebImage内部实现过程

    UIImageView+WebCache
    会先把 placeholderImage 显示,然后 SDWebImageManager 根据 URL 开始处理图片。
    - (void)sd_setImageWithURL:(nullable NSURL *)url
              placeholderImage:(nullable UIImage *)placeholder
                       options:(SDWebImageOptions)options;
    
    SDWebImageManager
    如果不在缓存中,则在给定URL处下载图像,否则返回缓存版本。
    - (nullable id <SDWebImageOperation>)loadImageWithURL:(nullable NSURL *)url
                                                  options:(SDWebImageOptions)options
                                                 progress:(nullable SDWebImageDownloaderProgressBlock)progressBlock
                                                completed:(nullable SDInternalCompletionBlock)completedBlock;
    
    SDImageCache
    异步查询缓存并在完成时调用完成的操作。
    - (nullable NSOperation *)queryCacheOperationForKey:(nullable NSString *)key options:(SDImageCacheOptions)options done:(nullable SDCacheQueryCompletedBlock)doneBlock;
    
    ######SDWebImageManager
    (1)内存磁盘和缓存中没有图片或者设置了强制更新url缓存即(SDWebImageRefreshCached)  需要下载图片
    设置了强制更新url缓存  ->  更新内存和磁盘缓存
    [self callCompletionBlockForOperation:strongOperation completion:completedBlock image:cachedImage data:cachedData error:nil cacheType:cacheType finished:YES url:url];
    ######SDWebImageDownloader
    (2)下载工具类根据url下载图片
    - (nullable SDWebImageDownloadToken *)downloadImageWithURL:(nullable NSURL *)url
                                                       options:(SDWebImageDownloaderOptions)options
                                                      progress:(nullable SDWebImageDownloaderProgressBlock)progressBlock
                                                     completed:(nullable SDWebImageDownloaderCompletedBlock)completedBlock;
    回调中 
    转换图片
    UIImage *transformedImage = [self.delegate imageManager:self transformDownloadedImage:downloadedImage withURL:url];
    储存图片到磁盘
    [self.imageCache storeImage:transformedImage imageData:cacheData forKey:key toDisk:cacheOnDisk completion:nil];
    ######SDWebImageManager
    [self callCompletionBlockForOperation:strongOperation completion:completedBlock image:cachedImage data:cachedData error:nil cacheType:cacheType finished:YES url:url];
    

    相关文章

      网友评论

          本文标题:SDWebImage内部实现过程

          本文链接:https://www.haomeiwen.com/subject/rppgnftx.html