SDWebImage是使用的NSURLSession來(lái)加載圖片的奋岁,而NSURLSession是自帶網(wǎng)絡(luò)緩存的板惑,當(dāng)遇到服務(wù)端url相同而圖片已經(jīng)修改的情況缀辩,SDWebImage默認(rèn)緩存是不會(huì)替換圖片的势告,這時(shí)我們可以用NSURLSession自帶的網(wǎng)絡(luò)緩存進(jìn)行圖片緩存没佑。
當(dāng)NSURLRequest的cachePolicy為NSURLRequestUseProtocolCachePolicy時(shí),緩存會(huì)遵循HTTPHeaderField設(shè)置的緩存協(xié)議方式务漩,比如設(shè)置HTTPHeaderField的key為@"Cache-Control"拄衰,value為@"must-revalidate"時(shí)會(huì)去對(duì)比請(qǐng)求頭,如果請(qǐng)求頭相同則取緩存的圖片饵骨,否則將重新加載翘悉。
SDWebImage中的SDWebImageRefreshCached枚舉是會(huì)設(shè)置cachePolicy為NSURLRequestUseProtocolCachePolicy的。SDWebImage中也給我們預(yù)留了HTTPHeaderField請(qǐng)求頭的設(shè)置居触。SDWebImageDownloader中的-setValue:forHTTPHeaderField:方法為添加請(qǐng)求頭的方法妖混。
但是SDWebImageDownloader是一個(gè)單例,修改單例屬性并不友好轮洋,而且我們并不是想所有的請(qǐng)求方法都使用這種請(qǐng)求方式制市。這時(shí)我們就需要自己新建個(gè)單例繼承與SDWebImageDownloader,重寫(xiě)其單例方法砖瞧,代碼如下:
@implementation LJWebImageMustRevalidateDownloader
+ (nonnull instancetype)sharedDownloader {
static dispatch_once_t once;
static LJWebImageMustRevalidateDownloader * instance;
dispatch_once(&once, ^{
instance = [self new];
[instance setValue:@"must-revalidate" forHTTPHeaderField:@"Cache-Control"];
});
return instance;
}
@end
但因?yàn)檎?qǐng)求參數(shù)屬性都是在SDWebImageManager中息堂,所有還需要新建一個(gè)以SDWebImageManager為父類的單例。SDWebImageManager中為我們預(yù)留了重新設(shè)置SDWebImageDownloader的方法块促,我們可以重寫(xiě)+defaultImageLoader方法為我們?cè)O(shè)置我們自己建的SDWebImageDownloader單例荣堰,代碼如下:
@implementation LJWebImageMustRevalidateManager
+ (nonnull instancetype)sharedManager {
static dispatch_once_t once;
static id instance;
dispatch_once(&once, ^{
instance = [self new];
});
return instance;
}
+ (id<SDImageLoader>)defaultImageLoader {
return [LJWebImageMustRevalidateDownloader sharedDownloader];
}
@end
直接調(diào)用SDWebImage中的網(wǎng)絡(luò)圖片請(qǐng)求方法,將我們自定義的SDWebImageManager傳入竭翠,代碼如下:
[imageView sd_setImageWithURL:url placeholderImage:placeholder options:SDWebImageRefreshCached context:@{SDWebImageContextCustomManager : [LJWebImageMustRevalidateManager sharedManager]}];