第四篇的寫在前面
本篇文章為SDWebImage源碼閱讀解析的最后一篇文章,主要介紹SDWebImage的圖片下載功能片橡。主要涉及兩個(gè)重要的類——SDWebImageDownloader
和SDWebImageDownloaderOperation
患雇。在第一篇介紹的SDWebImageManager
類中持有SDWebImageDownloader
屬性跃脊,通過loadImageWithURL()
方法調(diào)用SDWebImageDownloader
中的downloadImageWithURL()
方法對(duì)網(wǎng)絡(luò)圖片進(jìn)行下載。
本模塊的設(shè)計(jì)設(shè)計(jì)NSURLSession的使用苛吱,如果對(duì)這個(gè)類不熟悉的話酪术,可以參考官方開發(fā)者文檔URL Session Programming Guide。
//使用更新的downloaderOptions開啟下載圖片任務(wù)
SDWebImageDownloadToken *subOperationToken = [self.imageDownloader downloadImageWithURL:url options:downloaderOptions progress:progressBlock completed:^(UIImage *downloadedImage, NSData *downloadedData, NSError *error, BOOL finished) {
//do something...
}];
SDWebImageDownloader的設(shè)計(jì)
在SDWebImage中,SDWebImageDownloader
被設(shè)計(jì)為一個(gè)單例绘雁,與SDImageCache
和SDWebImageManagerd
類似橡疼。
用于管理
NSURLRequest
對(duì)象請(qǐng)求頭的封裝、緩存庐舟、cookie的設(shè)置欣除,加載選項(xiàng)的處理等功能。管理Operation之間的依賴關(guān)系挪略。SDWebImageDownloaderOperation
是一個(gè)自定義的并行Operation子類历帚。這個(gè)類主要實(shí)現(xiàn)了圖片下載的具體操作、以及圖片下載完成以后的圖片解壓縮杠娱、Operation生命周期管理等挽牢。
初始化方法和相關(guān)變量
SDWebImageDownloader
提供了一個(gè)全能初始化方法,在里面對(duì)一些屬性和變量做了初始化工作:
- (nonnull instancetype)initWithSessionConfiguration:(nullable NSURLSessionConfiguration *)sessionConfiguration {
if ((self = [super init])) {
_operationClass = [SDWebImageDownloaderOperation class];
//默認(rèn)需要對(duì)圖片進(jìn)行解壓
_shouldDecompressImages = YES;
//默認(rèn)的任務(wù)執(zhí)行方式為FIFO隊(duì)列
_executionOrder = SDWebImageDownloaderFIFOExecutionOrder;
_downloadQueue = [NSOperationQueue new];
//默認(rèn)最大并發(fā)任務(wù)的數(shù)目為6個(gè)
_downloadQueue.maxConcurrentOperationCount = 6;
_downloadQueue.name = @"com.hackemist.SDWebImageDownloader";
_URLOperations = [NSMutableDictionary new];
//設(shè)置默認(rèn)的HTTP請(qǐng)求頭
#ifdef SD_WEBP
_HTTPHeaders = [@{@"Accept": @"image/webp,image/*;q=0.8"} mutableCopy];
#else
_HTTPHeaders = [@{@"Accept": @"image/*;q=0.8"} mutableCopy];
#endif
_barrierQueue = dispatch_queue_create("com.hackemist.SDWebImageDownloaderBarrierQueue", DISPATCH_QUEUE_CONCURRENT);
//設(shè)置默認(rèn)的請(qǐng)求超時(shí)
_downloadTimeout = 15.0;
sessionConfiguration.timeoutIntervalForRequest = _downloadTimeout;
/**
*初始化session墨辛,delegateQueue設(shè)為nil因此session會(huì)創(chuàng)建一個(gè)串行任務(wù)隊(duì)列來處理代理方法
*和請(qǐng)求回調(diào)卓研。
*/
self.session = [NSURLSession sessionWithConfiguration:sessionConfiguration
delegate:self
delegateQueue:nil];
}
return self;
}
downloadImageWithURL()方法
downloadImageWithURL ()
是下載器的核心方法。
/**
* 通過創(chuàng)建異步下載器實(shí)例來根據(jù)url下載圖片
*
* 當(dāng)圖片下載完成后或者有錯(cuò)誤產(chǎn)生時(shí)將通知代理對(duì)象
*
*
* @param url The URL to the image to download
* @param options The options to be used for this download
* @param progressBlock 當(dāng)圖片在下載時(shí)progressBlock會(huì)被反復(fù)調(diào)用以通知下載進(jìn)度睹簇,該block在后臺(tái)隊(duì)列執(zhí)行
* @param completedBlock 圖片下載完成后執(zhí)行的回調(diào)block
*
* @return A token (SDWebImageDownloadToken) 返回的token可以被用在 -cancel 方法中取消任務(wù)
*/
- (nullable SDWebImageDownloadToken *)downloadImageWithURL:(nullable NSURL *)url
options:(SDWebImageDownloaderOptions)options
progress:(nullable SDWebImageDownloaderProgressBlock)progressBlock
completed:(nullable SDWebImageDownloaderCompletedBlock)completedBlock {
__weak SDWebImageDownloader *wself = self;
return [self addProgressCallback:progressBlock completedBlock:completedBlock forURL:url createCallback:^SDWebImageDownloaderOperation *{
__strong __typeof (wself) sself = wself;
//1. 設(shè)置超時(shí)
NSTimeInterval timeoutInterval = sself.downloadTimeout;
if (timeoutInterval == 0.0) {
timeoutInterval = 15.0;
}
//2. 關(guān)閉NSURLCache,防止重復(fù)緩存圖片請(qǐng)求
// In order to prevent from potential duplicate caching (NSURLCache + SDImageCache) we disable the cache for image requests if told otherwise
NSURLRequestCachePolicy cachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
//如果options中設(shè)置了使用NSURLCache則開啟NSURLCache寥闪,默認(rèn)關(guān)閉
if (options & SDWebImageDownloaderUseNSURLCache) {
if (options & SDWebImageDownloaderIgnoreCachedResponse) {
cachePolicy = NSURLRequestReturnCacheDataDontLoad;
} else {
cachePolicy = NSURLRequestUseProtocolCachePolicy;
}
}
//3. 初始化URLRequest
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url cachePolicy:cachePolicy timeoutInterval:timeoutInterval];
request.HTTPShouldHandleCookies = (options & SDWebImageDownloaderHandleCookies);
request.HTTPShouldUsePipelining = YES;
//4. 添加請(qǐng)求頭
if (sself.headersFilter) {
request.allHTTPHeaderFields = sself.headersFilter(url, [sself.HTTPHeaders copy]);
}
else {
request.allHTTPHeaderFields = sself.HTTPHeaders;
}
//5. 初始化operation 對(duì)象
SDWebImageDownloaderOperation *operation = [[sself.operationClass alloc] initWithRequest:request inSession:sself.session options:options];
operation.shouldDecompressImages = sself.shouldDecompressImages;
//6. 指定驗(yàn)證方式
if (sself.urlCredential) {
//SSL驗(yàn)證
operation.credential = sself.urlCredential;
} else if (sself.username && sself.password) {
//Basic驗(yàn)證
operation.credential = [NSURLCredential credentialWithUser:sself.username password:sself.password persistence:NSURLCredentialPersistenceForSession];
}
if (options & SDWebImageDownloaderHighPriority) {
operation.queuePriority = NSOperationQueuePriorityHigh;
} else if (options & SDWebImageDownloaderLowPriority) {
operation.queuePriority = NSOperationQueuePriorityLow;
}
//7. 將當(dāng)前operation添加到下載隊(duì)列
[sself.downloadQueue addOperation:operation];
if (sself.executionOrder == SDWebImageDownloaderLIFOExecutionOrder) {
//為operation添加依賴關(guān)系
//模擬棧的數(shù)據(jù)結(jié)構(gòu) 先進(jìn)后出
[sself.lastAddedOperation addDependency:operation];
sself.lastAddedOperation = operation;
}
return operation;
}];
}
在downloadImageWithURL
方法中太惠,直接返回了一個(gè)名為addProgressCallback
的方法,并將其中的代碼保存到block中傳給這個(gè)方法疲憋。
addProgressCallback方法
addProgressCallback
方法主要用于設(shè)置一些回調(diào)并且保存凿渊,并且執(zhí)行downloadImage
中保存的代碼將返回的operation
添加到數(shù)組中保存。block保存的數(shù)據(jù)結(jié)構(gòu)如下圖:
/** 為callbackBlocks添加callbackBlock->callbackBlock中包含:completedBlock缚柳,progressBlock
*
* @return SDWebImageDownloadToken
*/
- (nullable SDWebImageDownloadToken *)addProgressCallback:(SDWebImageDownloaderProgressBlock)progressBlock
completedBlock:(SDWebImageDownloaderCompletedBlock)completedBlock
forURL:(nullable NSURL *)url
createCallback:(SDWebImageDownloaderOperation *(^)())createCallback {
// 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.
//URL用于給 callbakcs 字典 設(shè)置鍵埃脏,因此不能為nil
//如果url == nil 直接執(zhí)行completedBlock回調(diào)
if (url == nil) {
if (completedBlock != nil) {
completedBlock(nil, nil, nil, NO);
}
return nil;
}
// 初始化 token 其實(shí)就是一個(gè)標(biāo)記
__block SDWebImageDownloadToken *token = nil;
// 在barrierQueue中同步執(zhí)行
dispatch_barrier_sync(self.barrierQueue, ^{
//1. 根據(jù)url獲取operation
SDWebImageDownloaderOperation *operation = self.URLOperations[url];
if (!operation) {
//2. operation不存在
//執(zhí)行operationCallback回調(diào)的代碼 初始化SDWebImageDownloaderOperation
operation = createCallback();
//3. 保存operation
self.URLOperations[url] = operation;
__weak SDWebImageDownloaderOperation *woperation = operation;
//4. 保存完成的回調(diào)代碼
operation.completionBlock = ^{
//下載完成后在字典中移除operation
SDWebImageDownloaderOperation *soperation = woperation;
if (!soperation) return;
if (self.URLOperations[url] == soperation) {
[self.URLOperations removeObjectForKey:url];
};
};
}
//5. 保存將回調(diào)保存到operation中的callbackBlocks數(shù)組 注意這是屬于operation的對(duì)象方法
id downloadOperationCancelToken = [operation addHandlersForProgress:progressBlock completed:completedBlock];
//6. 設(shè)置token的屬性
token = [SDWebImageDownloadToken new];
token.url = url;
token.downloadOperationCancelToken = downloadOperationCancelToken;
});
return token;
}
SDWebImageDownloaderOperation
Downloader部分的第二個(gè)類就是SDWebImageDownloaderOperation
在上面的部分也已經(jīng)用到過不少。它是NSOperation
的子類秋忙,如果對(duì)NSOperation
不熟悉的話彩掐,可以參考這篇文章。
內(nèi)部自定義了以下幾個(gè)通知:
NSString *const SDWebImageDownloadStartNotification = @"SDWebImageDownloadStartNotification";
NSString *const SDWebImageDownloadReceiveResponseNotification = @"SDWebImageDownloadReceiveResponseNotification";
NSString *const SDWebImageDownloadStopNotification = @"SDWebImageDownloadStopNotification";
NSString *const SDWebImageDownloadFinishNotification = @"SDWebImageDownloadFinishNotification";
對(duì)NSOperation
進(jìn)行自定義需要對(duì)以下幾個(gè)方法進(jìn)行重載:
/**
* 重寫NSOperation的start方法 在里面做處理
*/
- (void)start {
@synchronized (self) {
if (self.isCancelled) {
self.finished = YES;
[self reset];
return;
}
#if SD_UIKIT
//1. 進(jìn)行后臺(tái)任務(wù)的處理
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:^{
__strong __typeof (wself) sself = wself;
if (sself) {
[sself cancel];
[app endBackgroundTask:sself.backgroundTaskId];
sself.backgroundTaskId = UIBackgroundTaskInvalid;
}
}];
}
#endif
//2. 初始化session
NSURLSession *session = self.unownedSession;
if (!self.unownedSession) {
//如果Downloader沒有傳入session(self 對(duì) unownedSession弱引用灰追,因?yàn)槟J(rèn)該變量為downloader強(qiáng)引用)
//使用defaultSessionConfiguration初始化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
* delegate 設(shè)為 self 即需要自動(dòng)實(shí)現(xiàn)代理方法對(duì)任務(wù)進(jìn)行管理
* delegateQueue設(shè)為nil, 因此session會(huì)創(chuàng)建一個(gè)串行的任務(wù)隊(duì)列處理代理方法和回調(diào)
*/
self.ownedSession = [NSURLSession sessionWithConfiguration:sessionConfig
delegate:self
delegateQueue:nil];
session = self.ownedSession;
}
//使用request初始化dataTask
self.dataTask = [session dataTaskWithRequest:self.request];
self.executing = YES;
}
//開始執(zhí)行網(wǎng)絡(luò)請(qǐng)求
[self.dataTask resume];
if (self.dataTask) {
//對(duì)callbacks中的每個(gè)progressBlock進(jìn)行調(diào)用堵幽,并傳入進(jìn)度參數(shù)
//#define NSURLResponseUnknownLength ((long long)-1)
for (SDWebImageDownloaderProgressBlock progressBlock in [self callbacksForKey:kProgressCallbackKey]) {
progressBlock(0, NSURLResponseUnknownLength, self.request.URL);
}
//主隊(duì)列通知SDWebImageDownloadStartNotification
dispatch_async(dispatch_get_main_queue(), ^{
[[NSNotificationCenter defaultCenter] postNotificationName:SDWebImageDownloadStartNotification object:self];
});
} else {
//連接不成功
//執(zhí)行回調(diào)輸出錯(cuò)誤信息
[self callCompletionBlocksWithError:[NSError errorWithDomain:NSURLErrorDomain code:0 userInfo:@{NSLocalizedDescriptionKey : @"Connection can't be initialized"}]];
}
#if SD_UIKIT
Class UIApplicationClass = NSClassFromString(@"UIApplication");
if(!UIApplicationClass || ![UIApplicationClass respondsToSelector:@selector(sharedApplication)]) {
return;
}
if (self.backgroundTaskId != UIBackgroundTaskInvalid) {
UIApplication * app = [UIApplication performSelector:@selector(sharedApplication)];
[app endBackgroundTask:self.backgroundTaskId];
self.backgroundTaskId = UIBackgroundTaskInvalid;
}
#endif
}
/**
* 重寫NSOperation的cancel方法
*/
- (void)cancel {
@synchronized (self) {
[self cancelInternal];
}
}
/**
* 內(nèi)部方法cancel
*/
- (void)cancelInternal {
if (self.isFinished) return;
[super cancel];
if (self.dataTask) {
[self.dataTask cancel];
dispatch_async(dispatch_get_main_queue(), ^{
[[NSNotificationCenter defaultCenter] postNotificationName:SDWebImageDownloadStopNotification object:self];
});
// As we cancelled the connection, its callback won't be called and thus won't
// maintain the isFinished and isExecuting flags.
if (self.isExecuting) self.executing = NO;
if (!self.isFinished) self.finished = YES;
}
[self reset];
}
/**
* 重設(shè)operation
*/
- (void)reset {
dispatch_barrier_async(self.barrierQueue, ^{
[self.callbackBlocks removeAllObjects];
});
self.dataTask = nil;
self.imageData = nil;
if (self.ownedSession) {
[self.ownedSession invalidateAndCancel];
self.ownedSession = nil;
}
}
重點(diǎn)看start
方法。NSOperation中
需要執(zhí)行的代碼需要寫在start
方法中弹澎。
讓一個(gè)
NSOperation
操作開始朴下,你可以直接調(diào)用-start
,或者將它添加到NSOperationQueue
中苦蒿,添加之后殴胧,它會(huì)在隊(duì)列排到它以后自動(dòng)執(zhí)行。
類的內(nèi)部定義了兩個(gè)屬性作為任務(wù)的標(biāo)記:
@property (assign, nonatomic, getter = isExecuting) BOOL executing;
@property (assign, nonatomic, getter = isFinished) BOOL finished;
需要注意到的是佩迟,如果我們?cè)诼暶鲗傩缘臅r(shí)候使用了getter =
的語(yǔ)義团滥,則需要自己手動(dòng)寫getter
免胃,編譯器不會(huì)幫我們合成。源碼中手動(dòng)聲明了getter
方法惫撰,并實(shí)現(xiàn)KVO羔沙。
- (void)setFinished:(BOOL)finished {
[self willChangeValueForKey:@"isFinished"];
_finished = finished;
[self didChangeValueForKey:@"isFinished"];
}
- (void)setExecuting:(BOOL)executing {
[self willChangeValueForKey:@"isExecuting"];
_executing = executing;
[self didChangeValueForKey:@"isExecuting"];
}
在初始化NSURLSession
的時(shí)候,SDWebImageDownloaderOperation
將自己聲明為delegate
:
self.ownedSession = [NSURLSession sessionWithConfiguration:sessionConfig
delegate:self
delegateQueue:nil];
因此厨钻,需要實(shí)現(xiàn)NSURLSessionDelegate
代理方法扼雏。具體的實(shí)現(xiàn)這里不贅述,主要是針對(duì)各種情況進(jìn)行處理夯膀。但是需要注意到的是诗充,在SDWebImageDownloader
中同樣遵守了NSURLSessionDelegate
代理的方法,但是在downloader
中只是簡(jiǎn)單的把operation
數(shù)組中與task
對(duì)應(yīng)的operation
取出诱建,然后把對(duì)應(yīng)的參數(shù)傳入到SDWebImageDownloaderOperation
中的對(duì)應(yīng)的方法進(jìn)行處理蝴蜓。例如:
// 接收到服務(wù)器的響應(yīng)
- (void)URLSession:(NSURLSession *)session
dataTask:(NSURLSessionDataTask *)dataTask
didReceiveResponse:(NSURLResponse *)response
completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler {
// Identify the operation that runs this task and pass it the delegate method
SDWebImageDownloaderOperation *dataOperation = [self operationWithTask:dataTask];
//將參數(shù)傳入dataOperation中進(jìn)行處理
[dataOperation URLSession:session dataTask:dataTask didReceiveResponse:response completionHandler:completionHandler];
}
/**
* 根據(jù)task取出operation
*/
- (SDWebImageDownloaderOperation *)operationWithTask:(NSURLSessionTask *)task {
SDWebImageDownloaderOperation *returnOperation = nil;
for (SDWebImageDownloaderOperation *operation in self.downloadQueue.operations) {
if (operation.dataTask.taskIdentifier == task.taskIdentifier) {
returnOperation = operation;
break;
}
}
return returnOperation;
}
結(jié)尾
對(duì)于SDWebImage的主要功能在這四篇解析文章中大致的分析,除此以外的功能可能還需要對(duì)源碼進(jìn)行更深入的閱讀分析才能有更深的了解俺猿。由于筆者水平有限茎匠,未免出現(xiàn)有分析不準(zhǔn)確或者有不到位的地方,請(qǐng)見諒押袍。
源碼閱讀是一個(gè)需要耐心的過程诵冒,盡管在途中會(huì)遇到一些困難,但是只要多查資料多思考谊惭,就會(huì)有收獲汽馋。
參考文獻(xiàn):
- SDWebImage源碼閱讀
- iOS中使用像素位圖(CGImageRef)對(duì)圖片進(jìn)行處理
- 一張圖片引發(fā)的深思
- SDWebImage源碼解讀_之SDWebImageDecoder
- Difference between [UIImage imageNamed…] and [UIImage imageWithData…]?
- How-is-SDWebImage-better-than-X?
- Understanding SDWebImage - Decompression
- why decode image after [UIImage initwithData:] ?
- Image Resizing Techniques
- 多線程之NSOperation簡(jiǎn)介
- SDWebImage源碼閱讀筆記
- URL Session Programming Guide
- SDWebImage源碼解析
- Quartz 2D Programming Guide
- Avoiding Image Decompression Sickness
- NSOperation