美文网首页
源码探索 - SDWebImage

源码探索 - SDWebImage

作者: Jacky_夜火 | 来源:发表于2022-03-01 23:27 被阅读0次

    本次探索的SDWebImage版本为5.0之后的版本,其实总的来说,3.0之后的核心功能其实大差不差,更多的是bug的修补和扩展,本文主要写的还是这个库的核心模块。先看下系统的架构图


    SDWebImageHighLevelDiagram

    可以发现,核心模块其实就是Image Manager,以及它所使用的Image Cache和Image Loader。

    1、加载图片流程

    1.1 流程

    SDWebImageSequenceDiagram
    这张官方提供的时序图,已经清楚的告诉了我们整个SDWebImage的大致流程:
    (1)首先步骤1步骤2是SDWebImage对UIKit的一个扩展,可以通过这些方法快速调用SDWebImageManager对外提供的loadImage方法,也就是步骤3
    (2)步骤4说明了loadImage会去调用SDImageCachequeryImage方法去缓存中查询,如果缓存中存在则返回结果(步骤5),否则调用SDWebImageDownloaderloadImage方法下载(步骤6
    (3)下载后返回结果给SDWebImageManager(步骤7),同时执行SDImageCachestore方法进行存储操作(步骤8),然后返回给UIKit(步骤9和10

    实际上这个时序图的方法都是简写,源码中
    步骤3的方法是loadImageWithURL
    步骤4的方法是queryCacheOperationForKey
    步骤6的方法是downloadImageWithURL
    步骤8的方法是storeImage

    根据上面的流程,我们探索下代码

    1.2 代码探索

    // key is strong, value is weak because operation instance is retained by SDWebImageManager's runningOperations property
    // we should use lock to keep thread-safe because these method may not be accessed from main queue
    typedef NSMapTable<NSString *, id<SDWebImageOperation>> SDOperationsDictionary;
    
    - (void)sd_cancelImageLoadOperationWithKey:(nullable NSString *)key {
        if (key) {
            // Cancel in progress downloader from queue
            SDOperationsDictionary *operationDictionary = [self sd_operationDictionary];
            id<SDWebImageOperation> operation;
            
            @synchronized (self) {
                operation = [operationDictionary objectForKey:key];
            }
            if (operation) {
                if ([operation conformsToProtocol:@protocol(SDWebImageOperation)]) {
                    [operation cancel];
                }
                @synchronized (self) {
                    [operationDictionary removeObjectForKey:key];
                }
            }
        }
    }
    
    - (void)sd_internalSetImageWithURL:(nullable NSURL *)url
                      placeholderImage:(nullable UIImage *)placeholder
                               options:(SDWebImageOptions)options
                               context:(nullable SDWebImageContext *)context
                         setImageBlock:(nullable SDSetImageBlock)setImageBlock
                              progress:(nullable SDImageLoaderProgressBlock)progressBlock
                             completed:(nullable SDInternalCompletionBlock)completedBlock {
        if (context) {
            // copy to avoid mutable object
            context = [context copy];
        } else {
            context = [NSDictionary dictionary];
        }
        NSString *validOperationKey = context[SDWebImageContextSetImageOperationKey];
        if (!validOperationKey) {
            // pass through the operation key to downstream, which can used for tracing operation or image view class
            validOperationKey = NSStringFromClass([self class]);
            SDWebImageMutableContext *mutableContext = [context mutableCopy];
            mutableContext[SDWebImageContextSetImageOperationKey] = validOperationKey;
            context = [mutableContext copy];
        }
        self.sd_latestOperationKey = validOperationKey;
        //停止当前运行任务
        [self sd_cancelImageLoadOperationWithKey:validOperationKey];
        self.sd_imageURL = url;
        
        SDWebImageManager *manager = context[SDWebImageContextCustomManager];
        if (!manager) {
            manager = [SDWebImageManager sharedManager];
        } else {
            // remove this manager to avoid retain cycle (manger -> loader -> operation -> context -> manager)
            SDWebImageMutableContext *mutableContext = [context mutableCopy];
            mutableContext[SDWebImageContextCustomManager] = nil;
            context = [mutableContext copy];
        }
        
        BOOL shouldUseWeakCache = NO;
        if ([manager.imageCache isKindOfClass:SDImageCache.class]) {
            shouldUseWeakCache = ((SDImageCache *)manager.imageCache).config.shouldUseWeakMemoryCache;
        }
        //判断传入参数 options 中是否包含延时加载占位图,没有就在主线程中设置占位图
        if (!(options & SDWebImageDelayPlaceholder)) {
            if (shouldUseWeakCache) {
                NSString *key = [manager cacheKeyForURL:url context:context];
                // call memory cache to trigger weak cache sync logic, ignore the return value and go on normal query
                // this unfortunately will cause twice memory cache query, but it's fast enough
                // in the future the weak cache feature may be re-design or removed
                [((SDImageCache *)manager.imageCache) imageFromMemoryCacheForKey:key];
            }
            dispatch_main_async_safe(^{
                [self sd_setImage:placeholder imageData:nil basedOnClassOrViaCustomSetImageBlock:setImageBlock cacheType:SDImageCacheTypeNone imageURL:url];
            });
        }
        
        if (url) {
            // reset the progress
            NSProgress *imageProgress = objc_getAssociatedObject(self, @selector(sd_imageProgress));
            if (imageProgress) {
                imageProgress.totalUnitCount = 0;
                imageProgress.completedUnitCount = 0;
            }
            
    #if SD_UIKIT || SD_MAC
            // check and start image indicator
            [self sd_startImageIndicator];
            id<SDWebImageIndicator> imageIndicator = self.sd_imageIndicator;
    #endif
            //创建进度回调
            SDImageLoaderProgressBlock combinedProgressBlock = ^(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL) {
                if (imageProgress) {
                    imageProgress.totalUnitCount = expectedSize;
                    imageProgress.completedUnitCount = receivedSize;
                }
    #if SD_UIKIT || SD_MAC
                if ([imageIndicator respondsToSelector:@selector(updateIndicatorProgress:)]) {
                    double progress = 0;
                    if (expectedSize != 0) {
                        progress = (double)receivedSize / expectedSize;
                    }
                    progress = MAX(MIN(progress, 1), 0); // 0.0 - 1.0
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [imageIndicator updateIndicatorProgress:progress];
                    });
                }
    #endif
                if (progressBlock) {
                    progressBlock(receivedSize, expectedSize, targetURL);
                }
            };
            @weakify(self);
            //创建一个SDWebImageOperation,并且把它添加到当前视图任务HashMap中
            id <SDWebImageOperation> operation = [manager loadImageWithURL:url options:options context:context progress:combinedProgressBlock completed:^(UIImage *image, NSData *data, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
                @strongify(self);
                if (!self) { return; }
                // if the progress not been updated, mark it to complete state
                if (imageProgress && finished && !error && imageProgress.totalUnitCount == 0 && imageProgress.completedUnitCount == 0) {
                    imageProgress.totalUnitCount = SDWebImageProgressUnitCountUnknown;
                    imageProgress.completedUnitCount = SDWebImageProgressUnitCountUnknown;
                }
                
    #if SD_UIKIT || SD_MAC
                // check and stop image indicator
                if (finished) {
                    [self sd_stopImageIndicator];
                }
    #endif
                
                BOOL shouldCallCompletedBlock = finished || (options & SDWebImageAvoidAutoSetImage);
                BOOL shouldNotSetImage = ((image && (options & SDWebImageAvoidAutoSetImage)) ||
                                          (!image && !(options & SDWebImageDelayPlaceholder)));
                //加载后的图片处理,返回调用 or 直接显示
                SDWebImageNoParamsBlock callCompletedBlockClosure = ^{
                    if (!self) { return; }
                    if (!shouldNotSetImage) {
                        [self sd_setNeedsLayout];
                    }
                    if (completedBlock && shouldCallCompletedBlock) {
                        completedBlock(image, data, error, cacheType, finished, url);
                    }
                };
                
                // case 1a: we got an image, but the SDWebImageAvoidAutoSetImage flag is set
                // OR
                // case 1b: we got no image and the SDWebImageDelayPlaceholder is not set
                if (shouldNotSetImage) {
                    dispatch_main_async_safe(callCompletedBlockClosure);
                    return;
                }
                
                UIImage *targetImage = nil;
                NSData *targetData = nil;
                if (image) {
                    // case 2a: we got an image and the SDWebImageAvoidAutoSetImage is not set
                    targetImage = image;
                    targetData = data;
                } else if (options & SDWebImageDelayPlaceholder) {
                    // case 2b: we got no image and the SDWebImageDelayPlaceholder flag is set
                    targetImage = placeholder;
                    targetData = nil;
                }
                
    #if SD_UIKIT || SD_MAC
                // check whether we should use the image transition
                SDWebImageTransition *transition = nil;
                BOOL shouldUseTransition = NO;
                if (options & SDWebImageForceTransition) {
                    // Always
                    shouldUseTransition = YES;
                } else if (cacheType == SDImageCacheTypeNone) {
                    // From network
                    shouldUseTransition = YES;
                } else {
                    // From disk (and, user don't use sync query)
                    if (cacheType == SDImageCacheTypeMemory) {
                        shouldUseTransition = NO;
                    } else if (cacheType == SDImageCacheTypeDisk) {
                        if (options & SDWebImageQueryMemoryDataSync || options & SDWebImageQueryDiskDataSync) {
                            shouldUseTransition = NO;
                        } else {
                            shouldUseTransition = YES;
                        }
                    } else {
                        // Not valid cache type, fallback
                        shouldUseTransition = NO;
                    }
                }
                if (finished && shouldUseTransition) {
                    transition = self.sd_imageTransition;
                }
    #endif
                dispatch_main_async_safe(^{
    #if SD_UIKIT || SD_MAC
                    [self sd_setImage:targetImage imageData:targetData basedOnClassOrViaCustomSetImageBlock:setImageBlock transition:transition cacheType:cacheType imageURL:imageURL];
    #else
                    [self sd_setImage:targetImage imageData:targetData basedOnClassOrViaCustomSetImageBlock:setImageBlock cacheType:cacheType imageURL:imageURL];
    #endif
                    callCompletedBlockClosure();
                });
            }];
            [self sd_setImageLoadOperation:operation forKey:validOperationKey];
        } else {
    #if SD_UIKIT || SD_MAC
            [self sd_stopImageIndicator];
    #endif
            dispatch_main_async_safe(^{
                if (completedBlock) {
                    NSError *error = [NSError errorWithDomain:SDWebImageErrorDomain code:SDWebImageErrorInvalidURL userInfo:@{NSLocalizedDescriptionKey : @"Image url is nil"}];
                    completedBlock(nil, nil, error, SDImageCacheTypeNone, YES, url);
                }
            });
        }
    }
    

    这段代码其实是整个加载流程的核心代码,源码中的注释其实也挺清楚了,总结来说:

    1. 首先所有的任务都是存储在一个NSMapTable中,每次有新的任务进入时,先调用sd_cancelImageLoadOperationWithKey方法,通过 validOperationKey 值查询任务NSMapTable 存储任务,取消任务;
    2. 进行任务前的各种准备操作(设置占位图,进度,获取SDWebImageManager等),调用SDWebImageManager的loadImageWithURL方法进行设置,并把生成的任务operation保存在NSMapTable中;
    3. 加载完成之后,此时图片是否需要特殊处理(callCompletedBlockClosure),直接通过completedBlock回调 或者 调用sd_setImage后,直接调用sd_setNeedsLayout(标记刷新,下一次runloop就会刷新视图)

    2、缓存模块

    SDWebImage采用的是内存和磁盘双缓存的策略来实现缓存的

    • SDImageCache实现缓存逻辑
    • SDImageCacheConfig实现缓存配置

    2.1 内存缓存 - SDMemoryCache

    @interface SDMemoryCache <KeyType, ObjectType> : NSCache <KeyType, ObjectType> <SDMemoryCache>
    
    @property (nonatomic, strong, nonnull, readonly) SDImageCacheConfig *config;
    
    @end
    
    • SDMemoryCache继承了NSCache进行重写,因为系统提供的NSCache是会自行清理缓存,而且清理时间无法自行控制,这会导致当我们需要使用时可能已经被清理导致内存报错
    @interface SDMemoryCache <KeyType, ObjectType> () {
    #if SD_UIKIT
        SD_LOCK_DECLARE(_weakCacheLock); // a lock to keep the access to `weakCache` thread-safe
    #endif
    }
    @property (nonatomic, strong, nullable) SDImageCacheConfig *config;
    #if SD_UIKIT
    @property (nonatomic, strong, nonnull) NSMapTable<KeyType, ObjectType> *weakCache; // strong-weak cache
    #endif
    @end
    
    - (void)commonInit {
        SDImageCacheConfig *config = self.config;
        self.totalCostLimit = config.maxMemoryCost;
        self.countLimit = config.maxMemoryCount;
    
        [config addObserver:self forKeyPath:NSStringFromSelector(@selector(maxMemoryCost)) options:0 context:SDMemoryCacheContext];
        [config addObserver:self forKeyPath:NSStringFromSelector(@selector(maxMemoryCount)) options:0 context:SDMemoryCacheContext];
    
    #if SD_UIKIT
        self.weakCache = [[NSMapTable alloc] initWithKeyOptions:NSPointerFunctionsStrongMemory valueOptions:NSPointerFunctionsWeakMemory capacity:0];
        SD_LOCK_INIT(_weakCacheLock);
    
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(didReceiveMemoryWarning:)
                                                     name:UIApplicationDidReceiveMemoryWarningNotification
                                                   object:nil];
    #endif
    }
    
    // Current this seems no use on macOS (macOS use virtual memory and do not clear cache when memory warning). So we only override on iOS/tvOS platform.
    #if SD_UIKIT
    - (void)didReceiveMemoryWarning:(NSNotification *)notification {
        // Only remove cache, but keep weak cache
        [super removeAllObjects];
    }
    
    • SDMemoryCache 通过 NSMapTable 存储,并监听了 内存警告 didReceiveMemoryWarning 对内存缓存进行相应清理处理

    使用NSMapTable的原因:

    1. NSMapTable 类似于 NSDictionary,但 NSMapTable 可提供更多的内存语义。
    2. NSMapTable 中 key: strongMemory value: weakMemory 也就意味着,当前存储的value 弱引用,不会对其他对象产生任何影响,只是存在了全局的 weak表中,当对象释放时,对应的value就会被释放 ,即 NSMapTable 会自动删除当前的 key/Value;
      而如果使用NSDictionary,那么setValue:forKey: 中的key必须实现NSCoping协议,这时如果使用实例对象作为key时,NSDictionary会自动进行copy 其内存地址导致改变。
    // `setObject:forKey:` just call this with 0 cost. Override this is enough
    - (void)setObject:(id)obj forKey:(id)key cost:(NSUInteger)g {
       //存储到NSCache
        [super setObject:obj forKey:key cost:g];
        if (!self.config.shouldUseWeakMemoryCache) {
            return;
        }
        if (key && obj) {
            // Store weak cache
            SD_LOCK(_weakCacheLock);
            [self.weakCache setObject:obj forKey:key];
            SD_UNLOCK(_weakCacheLock);
        }
    }
    
    • 缓存会在 NSCache 中存一份,如果 shouldUseWeakMemoryCache 属性是YES的话,会再次在自己创建的 weakCache 中再存一份。也就会有两份内存
    - (id)objectForKey:(id)key {
        id obj = [super objectForKey:key];
        if (!self.config.shouldUseWeakMemoryCache) {
            return obj;
        }
        if (key && !obj) {
            // Check weak cache
            SD_LOCK(_weakCacheLock);
            obj = [self.weakCache objectForKey:key];
            SD_UNLOCK(_weakCacheLock);
            if (obj) {
                // Sync cache
                NSUInteger cost = 0;
                if ([obj isKindOfClass:[UIImage class]]) {
                    cost = [(UIImage *)obj sd_memoryCost];
                }
                [super setObject:obj forKey:key cost:cost];
            }
        }
        return obj;
    }
    
    • 尝试从NSCache获取缓存,但由于不可控,所以可能为nil,但如果设置了shouldUseWeakMemoryCache为YES,则会直接从自己创建的 weakCache 中获取,如果获取成功则同步回NSCache

    2.2 磁盘缓存 - SDDiskCache

    //SDImageCache
    - (nullable NSString *)cachePathForKey:(nullable NSString *)key {
        if (!key) {
            return nil;
        }
        return [self.diskCache cachePathForKey:key];
    }
    
    + (nullable NSString *)userCacheDirectory {
        NSArray<NSString *> *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
        return paths.firstObject;
    }
    
    - (void)migrateDiskCacheDirectory {
        if ([self.diskCache isKindOfClass:[SDDiskCache class]]) {
            static dispatch_once_t onceToken;
            dispatch_once(&onceToken, ^{
                // ~/Library/Caches/com.hackemist.SDImageCache/default/
                NSString *newDefaultPath = [[[self.class userCacheDirectory] stringByAppendingPathComponent:@"com.hackemist.SDImageCache"] stringByAppendingPathComponent:@"default"];
                // ~/Library/Caches/default/com.hackemist.SDWebImageCache.default/
                NSString *oldDefaultPath = [[[self.class userCacheDirectory] stringByAppendingPathComponent:@"default"] stringByAppendingPathComponent:@"com.hackemist.SDWebImageCache.default"];
                dispatch_async(self.ioQueue, ^{
                    [((SDDiskCache *)self.diskCache) moveCacheDirectoryFromPath:oldDefaultPath toPath:newDefaultPath];
                });
            });
        }
    }
    
    //SDDiskCache
    - (nullable NSString *)cachePathForKey:(NSString *)key {
        NSParameterAssert(key);
        return [self cachePathForKey:key inPath:self.diskCachePath];
    }
    
    - (nullable NSString *)cachePathForKey:(nullable NSString *)key inPath:(nonnull NSString *)path {
        NSString *filename = SDDiskCacheFileNameForKey(key);
        return [path stringByAppendingPathComponent:filename];
    }
    
    static inline NSString * _Nonnull SDDiskCacheFileNameForKey(NSString * _Nullable key) {
        const char *str = key.UTF8String;
        if (str == NULL) {
            str = "";
        }
        unsigned char r[CC_MD5_DIGEST_LENGTH];
        CC_MD5(str, (CC_LONG)strlen(str), r);
        NSURL *keyURL = [NSURL URLWithString:key];
        NSString *ext = keyURL ? keyURL.pathExtension : key.pathExtension;
        // File system has file name length limit, we need to check if ext is too long, we don't add it to the filename
        if (ext.length > SD_MAX_FILE_EXTENSION_LENGTH) {
            ext = nil;
        }
        NSString *filename = [NSString stringWithFormat:@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%@",
                              r[0], r[1], r[2], r[3], r[4], r[5], r[6], r[7], r[8], r[9], r[10],
                              r[11], r[12], r[13], r[14], r[15], ext.length == 0 ? @"" : [NSString stringWithFormat:@".%@", ext]];
        return filename;
    }
    
    • 在缓存文件夹中创建缓存目录,将缓存文件都以md5进行命名,保证了文件的唯一性
    //SDImageCache
    - (void)storeImage:(nullable UIImage *)image
             imageData:(nullable NSData *)imageData
                forKey:(nullable NSString *)key
              toMemory:(BOOL)toMemory
                toDisk:(BOOL)toDisk
            completion:(nullable SDWebImageNoParamsBlock)completionBlock {
        if (!image || !key) {
            if (completionBlock) {
                completionBlock();
            }
            return;
        }
        // if memory cache is enabled
        // 存入内存缓存
        if (toMemory && self.config.shouldCacheImagesInMemory) {
            NSUInteger cost = image.sd_memoryCost;
            [self.memoryCache setObject:image forKey:key cost:cost];
        }
        
        if (!toDisk) {
            if (completionBlock) {
                completionBlock();
            }
            return;
        }
        dispatch_async(self.ioQueue, ^{
            @autoreleasepool {
                NSData *data = imageData;
                if (!data && [image conformsToProtocol:@protocol(SDAnimatedImage)]) {
                    // If image is custom animated image class, prefer its original animated data
                    data = [((id<SDAnimatedImage>)image) animatedImageData];
                }
                if (!data && image) {
                    // Check image's associated image format, may return .undefined
                    SDImageFormat format = image.sd_imageFormat;
                    if (format == SDImageFormatUndefined) {
                        // If image is animated, use GIF (APNG may be better, but has bugs before macOS 10.14)
                        if (image.sd_isAnimated) {
                            format = SDImageFormatGIF;
                        } else {
                            // If we do not have any data to detect image format, check whether it contains alpha channel to use PNG or JPEG format
                            format = [SDImageCoderHelper CGImageContainsAlpha:image.CGImage] ? SDImageFormatPNG : SDImageFormatJPEG;
                        }
                    }
                    data = [[SDImageCodersManager sharedManager] encodedDataWithImage:image format:format options:nil];
                }
                [self _storeImageDataToDisk:data forKey:key];
                [self _archivedDataWithImage:image forKey:key];
            }
            
            if (completionBlock) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    completionBlock();
                });
            }
        });
    }
    
    • 存储时,先按需存储到内存,再按需存储到磁盘中
    - (nullable NSOperation *)queryCacheOperationForKey:(nullable NSString *)key options:(SDImageCacheOptions)options context:(nullable SDWebImageContext *)context cacheType:(SDImageCacheType)queryCacheType done:(nullable SDImageCacheQueryCompletionBlock)doneBlock {
        if (!key) {
            if (doneBlock) {
                doneBlock(nil, nil, SDImageCacheTypeNone);
            }
            return nil;
        }
        // Invalid cache type
        if (queryCacheType == SDImageCacheTypeNone) {
            if (doneBlock) {
                doneBlock(nil, nil, SDImageCacheTypeNone);
            }
            return nil;
        }
        
        // First check the in-memory cache...
        UIImage *image;
        if (queryCacheType != SDImageCacheTypeDisk) {
            image = [self imageFromMemoryCacheForKey:key];
        }
        
        if (image) {
            if (options & SDImageCacheDecodeFirstFrameOnly) {
                // Ensure static image
                Class animatedImageClass = image.class;
                if (image.sd_isAnimated || ([animatedImageClass isSubclassOfClass:[UIImage class]] && [animatedImageClass conformsToProtocol:@protocol(SDAnimatedImage)])) {
    #if SD_MAC
                    image = [[NSImage alloc] initWithCGImage:image.CGImage scale:image.scale orientation:kCGImagePropertyOrientationUp];
    #else
                    image = [[UIImage alloc] initWithCGImage:image.CGImage scale:image.scale orientation:image.imageOrientation];
    #endif
                }
            } else if (options & SDImageCacheMatchAnimatedImageClass) {
                // Check image class matching
                Class animatedImageClass = image.class;
                Class desiredImageClass = context[SDWebImageContextAnimatedImageClass];
                if (desiredImageClass && ![animatedImageClass isSubclassOfClass:desiredImageClass]) {
                    image = nil;
                }
            }
        }
    
        BOOL shouldQueryMemoryOnly = (queryCacheType == SDImageCacheTypeMemory) || (image && !(options & SDImageCacheQueryMemoryData));
        if (shouldQueryMemoryOnly) {
            if (doneBlock) {
                doneBlock(image, nil, SDImageCacheTypeMemory);
            }
            return nil;
        }
        
        // Second check the disk cache...
        NSOperation *operation = [NSOperation new];
        // Check whether we need to synchronously query disk
        // 1. in-memory cache hit & memoryDataSync
        // 2. in-memory cache miss & diskDataSync
        BOOL shouldQueryDiskSync = ((image && options & SDImageCacheQueryMemoryDataSync) ||
                                    (!image && options & SDImageCacheQueryDiskDataSync));
        void(^queryDiskBlock)(void) =  ^{
            if (operation.isCancelled) {
                if (doneBlock) {
                    doneBlock(nil, nil, SDImageCacheTypeNone);
                }
                return;
            }
            
            @autoreleasepool {
                NSData *diskData = [self diskImageDataBySearchingAllPathsForKey:key];
                UIImage *diskImage;
                if (image) {
                    // the image is from in-memory cache, but need image data
                    diskImage = image;
                } else if (diskData) {
                    BOOL shouldCacheToMomery = YES;
                    if (context[SDWebImageContextStoreCacheType]) {
                        SDImageCacheType cacheType = [context[SDWebImageContextStoreCacheType] integerValue];
                        shouldCacheToMomery = (cacheType == SDImageCacheTypeAll || cacheType == SDImageCacheTypeMemory);
                    }
                    // decode image data only if in-memory cache missed
                    diskImage = [self diskImageForKey:key data:diskData options:options context:context];
                    if (shouldCacheToMomery && diskImage && self.config.shouldCacheImagesInMemory) {
                        NSUInteger cost = diskImage.sd_memoryCost;
                        [self.memoryCache setObject:diskImage forKey:key cost:cost];
                    }
                }
                
                if (doneBlock) {
                    if (shouldQueryDiskSync) {
                        doneBlock(diskImage, diskData, SDImageCacheTypeDisk);
                    } else {
                        dispatch_async(dispatch_get_main_queue(), ^{
                            doneBlock(diskImage, diskData, SDImageCacheTypeDisk);
                        });
                    }
                }
            }
        };
        
        // Query in ioQueue to keep IO-safe
        if (shouldQueryDiskSync) {
            dispatch_sync(self.ioQueue, queryDiskBlock);
        } else {
            dispatch_async(self.ioQueue, queryDiskBlock);
        }
        
        return operation;
    }
    
    
    • 读取缓存时,首先通过key查询内存缓存
    • 如果没获取到image,则创建一个任务返回调用者,给调用者查询时使用
    • 通过diskImageDataBySearchingAllPathsForKey方法查找当前的文件目录和文件名,但由于整个查找会产生大量的缓存,所以用了@autoreleasepool进行优化
    • 查询到后将二进制NSData数据处理成UIImage,并按需添加到内存缓存中,同时返回

    3、下载模块

    SDWebImage下载的核心类是 SDWebImageDownloaderSDWebImageDownloaderOperation,所有的任务都会在下载完成后,在相应的 NSURLSessionDataDelegate 代理回调中处理相关数据.

    3.1 SDWebImageDownloader

    - (nullable SDWebImageDownloadToken *)downloadImageWithURL:(nullable NSURL *)url
                                                       options:(SDWebImageDownloaderOptions)options
                                                       context:(nullable SDWebImageContext *)context
                                                      progress:(nullable SDWebImageDownloaderProgressBlock)progressBlock
                                                     completed:(nullable SDWebImageDownloaderCompletedBlock)completedBlock {
        // The URL will be used as the key to the callbacks dictionary so it cannot be nil. If it is nil immediately call the completed block with no image or data.
        if (url == nil) {
            if (completedBlock) {
                NSError *error = [NSError errorWithDomain:SDWebImageErrorDomain code:SDWebImageErrorInvalidURL userInfo:@{NSLocalizedDescriptionKey : @"Image url is nil"}];
                completedBlock(nil, nil, error, YES);
            }
            return nil;
        }
        
        SD_LOCK(_operationsLock);
        id downloadOperationCancelToken;
        NSOperation<SDWebImageDownloaderOperation> *operation = [self.URLOperations objectForKey:url];
        // There is a case that the operation may be marked as finished or cancelled, but not been removed from `self.URLOperations`.
        if (!operation || operation.isFinished || operation.isCancelled) {
            operation = [self createDownloaderOperationWithUrl:url options:options context:context];
            if (!operation) {
                SD_UNLOCK(_operationsLock);
                if (completedBlock) {
                    NSError *error = [NSError errorWithDomain:SDWebImageErrorDomain code:SDWebImageErrorInvalidDownloadOperation userInfo:@{NSLocalizedDescriptionKey : @"Downloader operation is nil"}];
                    completedBlock(nil, nil, error, YES);
                }
                return nil;
            }
            @weakify(self);
            operation.completionBlock = ^{
                @strongify(self);
                if (!self) {
                    return;
                }
                SD_LOCK(self->_operationsLock);
                [self.URLOperations removeObjectForKey:url];
                SD_UNLOCK(self->_operationsLock);
            };
            self.URLOperations[url] = operation;
            // Add the handlers before submitting to operation queue, avoid the race condition that operation finished before setting handlers.
            downloadOperationCancelToken = [operation addHandlersForProgress:progressBlock completed:completedBlock];
            // Add operation to operation queue only after all configuration done according to Apple's doc.
            // `addOperation:` does not synchronously execute the `operation.completionBlock` so this will not cause deadlock.
            [self.downloadQueue addOperation:operation];
        } else {
            // When we reuse the download operation to attach more callbacks, there may be thread safe issue because the getter of callbacks may in another queue (decoding queue or delegate queue)
            // So we lock the operation here, and in `SDWebImageDownloaderOperation`, we use `@synchonzied (self)`, to ensure the thread safe between these two classes.
            @synchronized (operation) {
                downloadOperationCancelToken = [operation addHandlersForProgress:progressBlock completed:completedBlock];
            }
            if (!operation.isExecuting) {
                if (options & SDWebImageDownloaderHighPriority) {
                    operation.queuePriority = NSOperationQueuePriorityHigh;
                } else if (options & SDWebImageDownloaderLowPriority) {
                    operation.queuePriority = NSOperationQueuePriorityLow;
                } else {
                    operation.queuePriority = NSOperationQueuePriorityNormal;
                }
            }
        }
        SD_UNLOCK(_operationsLock);
        
        SDWebImageDownloadToken *token = [[SDWebImageDownloadToken alloc] initWithDownloadOperation:operation];
        token.url = url;
        token.request = operation.request;
        token.downloadOperationCancelToken = downloadOperationCancelToken;
        
        return token;
    }
    
    - (nullable NSOperation<SDWebImageDownloaderOperation> *)createDownloaderOperationWithUrl:(nonnull NSURL *)url
                                                                                      options:(SDWebImageDownloaderOptions)options
                                                                                      context:(nullable SDWebImageContext *)context {
        NSTimeInterval timeoutInterval = self.config.downloadTimeout;
        if (timeoutInterval == 0.0) {
            timeoutInterval = 15.0;
        }
        
        // In order to prevent from potential duplicate caching (NSURLCache + SDImageCache) we disable the cache for image requests if told otherwise
        NSURLRequestCachePolicy cachePolicy = options & SDWebImageDownloaderUseNSURLCache ? NSURLRequestUseProtocolCachePolicy : NSURLRequestReloadIgnoringLocalCacheData;
        NSMutableURLRequest *mutableRequest = [[NSMutableURLRequest alloc] initWithURL:url cachePolicy:cachePolicy timeoutInterval:timeoutInterval];
        mutableRequest.HTTPShouldHandleCookies = SD_OPTIONS_CONTAINS(options, SDWebImageDownloaderHandleCookies);
        mutableRequest.HTTPShouldUsePipelining = YES;
        SD_LOCK(_HTTPHeadersLock);
        mutableRequest.allHTTPHeaderFields = self.HTTPHeaders;
        SD_UNLOCK(_HTTPHeadersLock);
        
        // Context Option
        SDWebImageMutableContext *mutableContext;
        if (context) {
            mutableContext = [context mutableCopy];
        } else {
            mutableContext = [NSMutableDictionary dictionary];
        }
        
        // Request Modifier
        id<SDWebImageDownloaderRequestModifier> requestModifier;
        if ([context valueForKey:SDWebImageContextDownloadRequestModifier]) {
            requestModifier = [context valueForKey:SDWebImageContextDownloadRequestModifier];
        } else {
            requestModifier = self.requestModifier;
        }
        
        NSURLRequest *request;
        if (requestModifier) {
            NSURLRequest *modifiedRequest = [requestModifier modifiedRequestWithRequest:[mutableRequest copy]];
            // If modified request is nil, early return
            if (!modifiedRequest) {
                return nil;
            } else {
                request = [modifiedRequest copy];
            }
        } else {
            request = [mutableRequest copy];
        }
        // Response Modifier
        id<SDWebImageDownloaderResponseModifier> responseModifier;
        if ([context valueForKey:SDWebImageContextDownloadResponseModifier]) {
            responseModifier = [context valueForKey:SDWebImageContextDownloadResponseModifier];
        } else {
            responseModifier = self.responseModifier;
        }
        if (responseModifier) {
            mutableContext[SDWebImageContextDownloadResponseModifier] = responseModifier;
        }
        // Decryptor
        id<SDWebImageDownloaderDecryptor> decryptor;
        if ([context valueForKey:SDWebImageContextDownloadDecryptor]) {
            decryptor = [context valueForKey:SDWebImageContextDownloadDecryptor];
        } else {
            decryptor = self.decryptor;
        }
        if (decryptor) {
            mutableContext[SDWebImageContextDownloadDecryptor] = decryptor;
        }
        
        context = [mutableContext copy];
        
        // Operation Class
        Class operationClass = self.config.operationClass;
        if (operationClass && [operationClass isSubclassOfClass:[NSOperation class]] && [operationClass conformsToProtocol:@protocol(SDWebImageDownloaderOperation)]) {
            // Custom operation class
        } else {
            operationClass = [SDWebImageDownloaderOperation class];
        }
        NSOperation<SDWebImageDownloaderOperation> *operation = [[operationClass alloc] initWithRequest:request inSession:self.session options:options context:context];
        
        if ([operation respondsToSelector:@selector(setCredential:)]) {
            if (self.config.urlCredential) {
                operation.credential = self.config.urlCredential;
            } else if (self.config.username && self.config.password) {
                operation.credential = [NSURLCredential credentialWithUser:self.config.username password:self.config.password persistence:NSURLCredentialPersistenceForSession];
            }
        }
            
        if ([operation respondsToSelector:@selector(setMinimumProgressInterval:)]) {
            operation.minimumProgressInterval = MIN(MAX(self.config.minimumProgressInterval, 0), 1);
        }
        
        if ([operation respondsToSelector:@selector(setAcceptableStatusCodes:)]) {
            operation.acceptableStatusCodes = self.config.acceptableStatusCodes;
        }
        
        if ([operation respondsToSelector:@selector(setAcceptableContentTypes:)]) {
            operation.acceptableContentTypes = self.config.acceptableContentTypes;
        }
        
        if (options & SDWebImageDownloaderHighPriority) {
            operation.queuePriority = NSOperationQueuePriorityHigh;
        } else if (options & SDWebImageDownloaderLowPriority) {
            operation.queuePriority = NSOperationQueuePriorityLow;
        }
        
        //下载优先级
        if (self.config.executionOrder == SDWebImageDownloaderLIFOExecutionOrder) {
            // Emulate LIFO execution order by systematically, each previous adding operation can dependency the new operation
            // This can gurantee the new operation to be execulated firstly, even if when some operations finished, meanwhile you appending new operations
            // Just make last added operation dependents new operation can not solve this problem. See test case #test15DownloaderLIFOExecutionOrder
            for (NSOperation *pendingOperation in self.downloadQueue.operations) {
                [pendingOperation addDependency:operation];
            }
        }
        
        return operation;
    }
    
    
    typedef NS_ENUM(NSInteger, SDWebImageDownloaderExecutionOrder) {
        /**
         * Default value. All download operations will execute in queue style (first-in-first-out).
         */
        SDWebImageDownloaderFIFOExecutionOrder,
        
        /**
         * All download operations will execute in stack style (last-in-first-out).
         */
        SDWebImageDownloaderLIFOExecutionOrder
    };
    
    • downloadImageWithURL处理了SDWebImage的下载逻辑,通过createDownloaderOperationWithUrl方法创建了下载任务
    • createDownloaderOperationWithUrl内设置了下载任务的优先级,SDWebImage只有两种方式,即默认的FIFO(先进先出),以及LIFO(后进先出)

    3.2 SDWebImageDownloaderOperation

    /**
     Describes a downloader operation. If one wants to use a custom downloader op, it needs to inherit from `NSOperation` and conform to this protocol
     For the description about these methods, see `SDWebImageDownloaderOperation`
     @note If your custom operation class does not use `NSURLSession` at all, do not implement the optional methods and session delegate methods.
     */
    @protocol SDWebImageDownloaderOperation <NSURLSessionTaskDelegate, NSURLSessionDataDelegate>
    @required
    - (nonnull instancetype)initWithRequest:(nullable NSURLRequest *)request
                                  inSession:(nullable NSURLSession *)session
                                    options:(SDWebImageDownloaderOptions)options;
    
    - (nonnull instancetype)initWithRequest:(nullable NSURLRequest *)request
                                  inSession:(nullable NSURLSession *)session
                                    options:(SDWebImageDownloaderOptions)options
                                    context:(nullable SDWebImageContext *)context;
    
    - (nullable id)addHandlersForProgress:(nullable SDWebImageDownloaderProgressBlock)progressBlock
                                completed:(nullable SDWebImageDownloaderCompletedBlock)completedBlock;
    
    - (BOOL)cancel:(nullable id)token;
    
    @property (strong, nonatomic, readonly, nullable) NSURLRequest *request;
    @property (strong, nonatomic, readonly, nullable) NSURLResponse *response;
    
    @optional
    @property (strong, nonatomic, readonly, nullable) NSURLSessionTask *dataTask;
    @property (strong, nonatomic, readonly, nullable) NSURLSessionTaskMetrics *metrics API_AVAILABLE(macosx(10.12), ios(10.0), watchos(3.0), tvos(10.0));
    
    // These operation-level config was inherited from downloader. See `SDWebImageDownloaderConfig` for documentation.
    @property (strong, nonatomic, nullable) NSURLCredential *credential;
    @property (assign, nonatomic) double minimumProgressInterval;
    @property (copy, nonatomic, nullable) NSIndexSet *acceptableStatusCodes;
    @property (copy, nonatomic, nullable) NSSet<NSString *> *acceptableContentTypes;
    
    @end
    
    @interface SDWebImageDownloaderOperation : NSOperation <SDWebImageDownloaderOperation>
    
    - (void)start {
        @synchronized (self) {
            if (self.isCancelled) {
                if (!self.isFinished) self.finished = YES;
                // Operation cancelled by user before sending the request
                [self callCompletionBlocksWithError:[NSError errorWithDomain:SDWebImageErrorDomain code:SDWebImageErrorCancelled userInfo:@{NSLocalizedDescriptionKey : @"Operation cancelled by user before sending the request"}]];
                [self reset];
                return;
            }
    
    #if SD_UIKIT
            Class UIApplicationClass = NSClassFromString(@"UIApplication");
            BOOL hasApplication = UIApplicationClass && [UIApplicationClass respondsToSelector:@selector(sharedApplication)];
            if (hasApplication && [self shouldContinueWhenAppEntersBackground]) {
                __weak typeof(self) wself = self;
                UIApplication * app = [UIApplicationClass performSelector:@selector(sharedApplication)];
                self.backgroundTaskId = [app beginBackgroundTaskWithExpirationHandler:^{
                    [wself cancel];
                }];
            }
    #endif
            NSURLSession *session = self.unownedSession;
            if (!session) {
                NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
                sessionConfig.timeoutIntervalForRequest = 15;
                
                /**
                 *  Create the session for this task
                 *  We send nil as delegate queue so that the session creates a serial operation queue for performing all delegate
                 *  method calls and completion handler calls.
                 */
                session = [NSURLSession sessionWithConfiguration:sessionConfig
                                                        delegate:self
                                                   delegateQueue:nil];
                self.ownedSession = session;
            }
            
            if (self.options & SDWebImageDownloaderIgnoreCachedResponse) {
                // Grab the cached data for later check
                NSURLCache *URLCache = session.configuration.URLCache;
                if (!URLCache) {
                    URLCache = [NSURLCache sharedURLCache];
                }
                NSCachedURLResponse *cachedResponse;
                // NSURLCache's `cachedResponseForRequest:` is not thread-safe, see https://developer.apple.com/documentation/foundation/nsurlcache#2317483
                @synchronized (URLCache) {
                    cachedResponse = [URLCache cachedResponseForRequest:self.request];
                }
                if (cachedResponse) {
                    self.cachedData = cachedResponse.data;
                    self.response = cachedResponse.response;
                }
            }
            
            if (!session.delegate) {
                // Session been invalid and has no delegate at all
                [self callCompletionBlocksWithError:[NSError errorWithDomain:SDWebImageErrorDomain code:SDWebImageErrorInvalidDownloadOperation userInfo:@{NSLocalizedDescriptionKey : @"Session delegate is nil and invalid"}]];
                [self reset];
                return;
            }
            
            self.dataTask = [session dataTaskWithRequest:self.request];
            self.executing = YES;
        }
    
        if (self.dataTask) {
            if (self.options & SDWebImageDownloaderHighPriority) {
                self.dataTask.priority = NSURLSessionTaskPriorityHigh;
                self.coderQueue.qualityOfService = NSQualityOfServiceUserInteractive;
            } else if (self.options & SDWebImageDownloaderLowPriority) {
                self.dataTask.priority = NSURLSessionTaskPriorityLow;
                self.coderQueue.qualityOfService = NSQualityOfServiceBackground;
            } else {
                self.dataTask.priority = NSURLSessionTaskPriorityDefault;
                self.coderQueue.qualityOfService = NSQualityOfServiceDefault;
            }
            [self.dataTask resume];
            for (SDWebImageDownloaderProgressBlock progressBlock in [self callbacksForKey:kProgressCallbackKey]) {
                progressBlock(0, NSURLResponseUnknownLength, self.request.URL);
            }
            __block typeof(self) strongSelf = self;
            dispatch_async(dispatch_get_main_queue(), ^{
                [[NSNotificationCenter defaultCenter] postNotificationName:SDWebImageDownloadStartNotification object:strongSelf];
            });
        } else {
            if (!self.isFinished) self.finished = YES;
            [self callCompletionBlocksWithError:[NSError errorWithDomain:SDWebImageErrorDomain code:SDWebImageErrorInvalidDownloadOperation userInfo:@{NSLocalizedDescriptionKey : @"Task can't be initialized"}]];
            [self reset];
        }
    }
    
    - (void)cancel {
        @synchronized (self) {
            [self cancelInternal];
        }
    }
    
    • SDWebImageDownloaderOperation继承自NSOperation,也继承了 NSURLSessionDataDelegate 协议,并重写了 start
    • start方法中创建了下载使用的** NSURLSession**对象,开启了图片的下载,并抛出一个下载开始的通知

    相关文章

      网友评论

          本文标题:源码探索 - SDWebImage

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