美文网首页
SDWebImage源码之SDWebImageManager

SDWebImage源码之SDWebImageManager

作者: Cyyyyyyyy | 来源:发表于2017-05-28 15:07 被阅读266次

    前面的两篇文章简单分析了SDImageCache
    SDWebImageDownloader的代码。它们分别实现了图片的缓存和下载。现在,还需要一个统一的类把它们的功能组合到一起,方便用户调用。这个类就是SDWebImageManager


    以下代码和分析都基于041842bf085cbb711f0d9e099e6acbf6fd533b0c这个commit。

    SDWebImageManager

    - (nonnull instancetype)init {
        SDImageCache *cache = [SDImageCache sharedImageCache];
        SDWebImageDownloader *downloader = [SDWebImageDownloader sharedDownloader];
        return [self initWithCache:cache downloader:downloader];
    }
    
    - (nonnull instancetype)initWithCache:(nonnull SDImageCache *)cache downloader:(nonnull SDWebImageDownloader *)downloader {
        if ((self = [super init])) {
            _imageCache = cache;
            _imageDownloader = downloader;
            _failedURLs = [NSMutableSet new];
            _runningOperations = [NSMutableArray new];
        }
        return self;
    }
    

    SDWebImageManager提供了可以设置指定的SDImageCacheSDWebImageDownloaderinit方法,方便调用方根据需要设置自己的SDImageCacheSDWebImageDownloader的实例。这种依赖注入的设计方式也可以方便单元测试时注入mock的对象。

    /**
     * The cache filter is a block used each time SDWebImageManager need to convert an URL into a cache key. This can
     * be used to remove dynamic part of an image URL.
     *
     * The following example sets a filter in the application delegate that will remove any query-string from the
     * URL before to use it as a cache key:
     *
     * @code
    
    [[SDWebImageManager sharedManager] setCacheKeyFilter:^(NSURL *url) {
        url = [[NSURL alloc] initWithScheme:url.scheme host:url.host path:url.path];
        return [url absoluteString];
    }];
    
     * @endcode
     */
    @property (nonatomic, copy, nullable) SDWebImageCacheKeyFilterBlock cacheKeyFilter;
    
    - (nullable NSString *)cacheKeyForURL:(nullable NSURL *)url {
        if (!url) {
            return @"";
        }
    
        if (self.cacheKeyFilter) {
            return self.cacheKeyFilter(url);
        } else {
            return url.absoluteString;
        }
    }
    
    - (void)diskImageExistsForURL:(nullable NSURL *)url
                       completion:(nullable SDWebImageCheckCacheCompletionBlock)completionBlock {
        NSString *key = [self cacheKeyForURL:url];
        
        [self.imageCache diskImageExistsWithKey:key completion:^(BOOL isInDiskCache) {
            // the completion block of checkDiskCacheForImageWithKey:completion: is always called on the main queue, no need to further dispatch
            if (completionBlock) {
                completionBlock(isInDiskCache);
            }
        }];
    }
    

    SDImageCache只管以key为唯一标识保存图片;SDWebImageDownloader只管依照图片URL下载图片,这里的cacheKeyFilter决定了URL应该被怎样处理成图片缓存用的key。

    @interface SDWebImageCombinedOperation : NSObject <SDWebImageOperation>
    
    @property (assign, nonatomic, getter = isCancelled) BOOL cancelled;
    @property (copy, nonatomic, nullable) SDWebImageNoParamsBlock cancelBlock;
    @property (strong, nonatomic, nullable) NSOperation *cacheOperation;
    
    @end
    
    @interface SDWebImageManager ()
    
    @property (strong, nonatomic, nonnull) NSMutableArray<SDWebImageCombinedOperation *> *runningOperations;
    
    @end
    

    这里设计了一个SDWebImageCombinedOperation类,并维护了一个数组runningOperations对其进行管理。

    loadImageWithURL加载图片有两个步骤,查询和下载。SDWebImageCombinedOperation同时代表了缓存查询和下载这两种行为。
    这里的流程代码也比较多,用文字理一下:

    1. 初始化loadImageWithURL方法被调用时,把SDWebImageCombinedOperation加到runningOperations里。
    2. 查询:到SDImageCache里查询图片是否存在,把查询缓存用的NSOperation保存在SDWebImageCombinedOperation里。
    3. 查询结束:如果图片在缓存中,回调completedBlock,把SDWebImageCombinedOperationrunningOperations里去掉。否则开始下载。
    4. 下载:调用SDWebImageDownloader下载图片,并且把SDWebImageCombinedOperationcancelBlock设置成取消下载。
    5. 下载结束:图片下载完成后,回调completedBlock,并把SDWebImageCombinedOperationrunningOperations里去掉。

    可以看到,只要加载图片的过程在进行,无论是查询还是下载,这个任务都会在runningOperations里,外部可以统一的查询和管理图片加载的任务。

    operation.cacheOperation = [self.imageCache queryCacheOperationForKey:key done:^(UIImage *cachedImage, NSData *cachedData, SDImageCacheType cacheType) {
            if (operation.isCancelled) {
                [self safelyRemoveOperationFromRunning:operation];
                return;
            }
            ...
    }];
                operation.cancelBlock = ^{
                    [self.imageDownloader cancel:subOperationToken];
                    __strong __typeof(weakOperation) strongOperation = weakOperation;
                    [self safelyRemoveOperationFromRunning:strongOperation];
                };
    

    要注意的是,如果在查询过程中,调用取消任务并不会中止查询流程,只是在最终返回时直接丢掉查询结果;而如果在下载过程中,调用cancel最后会调用到SDWebImageDownloader的cancel,真正取消下载任务。

    - (void)cancelAll {
        @synchronized (self.runningOperations) {
            NSArray<SDWebImageCombinedOperation *> *copiedOperations = [self.runningOperations copy];
            [copiedOperations makeObjectsPerformSelector:@selector(cancel)];
            [self.runningOperations removeObjectsInArray:copiedOperations];
        }
    }
    
    - (BOOL)isRunning {
        BOOL isRunning = NO;
        @synchronized (self.runningOperations) {
            isRunning = (self.runningOperations.count > 0);
        }
        return isRunning;
    }
    
    - (void)safelyRemoveOperationFromRunning:(nullable SDWebImageCombinedOperation*)operation {
        @synchronized (self.runningOperations) {
            if (operation) {
                [self.runningOperations removeObject:operation];
            }
        }
    }
    

    为了防止self.runningOperations被多线程操作,所有对self.runningOperations的访问都加上了@synchronized临界区,@synchronized里的代码段不会同时在多个线程中被执行。

    SDWebImageManagerTests

    NSString *workingImageURL = @"http://s3.amazonaws.com/fast-image-cache/demo-images/FICDDemoImage001.jpg";
    
    (void)test02ThatDownloadInvokesCompletionBlockWithCorrectParamsAsync {
        __block XCTestExpectation *expectation = [self expectationWithDescription:@"Image download completes"];
    
        NSURL *originalImageURL = [NSURL URLWithString:workingImageURL];
        
        [[SDWebImageManager sharedManager] loadImageWithURL:originalImageURL
                                                    options:SDWebImageRefreshCached
                                                   progress:nil
                                                  completed:^(UIImage *image, NSData *data, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
            expect(image).toNot.beNil();
            expect(error).to.beNil();
            expect(originalImageURL).to.equal(imageURL);
    
            [expectation fulfill];
            expectation = nil;
        }];
        expect([[SDWebImageManager sharedManager] isRunning]).to.equal(YES);
    
        [self waitForExpectationsWithTimeout:kAsyncTestTimeout handler:nil];
    }
    

    SDWebImage的单元测试依赖了网络访问,这个不太好。我们开发中需要做类似功能的单元测试时,可以考虑用OHHTTPStubs来搞些假的网络请求。


    SDWebImage源码系列

    SDWebImage源码之SDImageCache
    SDWebImage源码之SDWebImageDownloader
    SDWebImage源码之SDWebImageManager

    相关文章

      网友评论

          本文标题:SDWebImage源码之SDWebImageManager

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