1. [imageview sd_setImageWithURL:[NSURL URLWithString:imageUrlString] placeholderImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle]pathForResource:kDefaultAvatarIcon ofType:kPngName]] options:SDWebImageRefreshCached completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
}];
將options 設(shè)置為SDWebImageRefreshCached
2.appdelegate中didfinishlunch 中添加如下方法
-(void)sdWEbDownloaderRegister{
SDWebImageDownloader *imgDownloader = SDWebImageManager.sharedManager.imageDownloader;
imgDownloader.headersFilter? = ^NSDictionary *(NSURL *url, NSDictionary *headers) {
NSFileManager *fm = [[NSFileManager alloc] init];
NSString *imgKey = [SDWebImageManager.sharedManager cacheKeyForURL:url];
NSString *imgPath = [SDWebImageManager.sharedManager.imageCache defaultCachePathForKey:imgKey];
NSDictionary *fileAttr = [fm attributesOfItemAtPath:imgPath error:nil];
NSMutableDictionary *mutableHeaders = [headers mutableCopy];
NSDate *lastModifiedDate = nil;
if (fileAttr.count > 0) {
if (fileAttr.count > 0) {
lastModifiedDate = (NSDate *)fileAttr[NSFileModificationDate];
}
}
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
formatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
formatter.dateFormat = @"EEE, dd MMM yyyy HH:mm:ss z";
NSString *lastModifiedStr = [formatter stringFromDate:lastModifiedDate];
lastModifiedStr = lastModifiedStr.length > 0 ? lastModifiedStr : @"";
[mutableHeaders setValue:lastModifiedStr forKey:@"If-Modified-Since"];
return mutableHeaders;
};
}
加上以上代碼,sdwebimage在下載圖片前會(huì)將上次獲取的Etag、Last-Modified和本次需要下載的圖片的Etag、Last-Modified比對(duì),若一致不會(huì)下載,若不一致說明有更新
Etag由服務(wù)器端生成,客戶端通過If-Match或者說If-None-Match這個(gè)條件判斷請(qǐng)求來驗(yàn)證資源是否修改。常見的是使用If-None-Match.請(qǐng)求一個(gè)文件的流程可能如下:
====第一次請(qǐng)求===
1.客戶端發(fā)起 HTTP GET 請(qǐng)求一個(gè)文件;
2.服務(wù)器處理請(qǐng)求,返回文件內(nèi)容和一堆Header,當(dāng)然包括Etag(例如"2e681a-6-5d044840")(假設(shè)服務(wù)器支持Etag生成和已經(jīng)開啟了Etag).狀態(tài)碼200
====第二次請(qǐng)求===
1.客戶端發(fā)起 HTTP GET 請(qǐng)求一個(gè)文件,注意這個(gè)時(shí)候客戶端同時(shí)發(fā)送一個(gè)If-None-Match頭,這個(gè)頭的內(nèi)容就是第一次請(qǐng)求時(shí)服務(wù)器返回的Etag:2e681a-6-5d044840
2.服務(wù)器判斷發(fā)送過來的Etag和計(jì)算出來的Etag匹配,因此If-None-Match為False,不返回200,返回304,客戶端繼續(xù)使用
sdwebimage有一段代碼如下:
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
//'304 Not Modified' is an exceptional one
if (![response respondsToSelector:@selector(statusCode)] || ([((NSHTTPURLResponse *)response) statusCode] < 400 && [((NSHTTPURLResponse *)response) statusCode] != 304)) {
NSInteger expected = response.expectedContentLength > 0 ? (NSInteger)response.expectedContentLength : 0;
self.expectedSize = expected;
if (self.progressBlock) {
self.progressBlock(0, expected);
}
self.imageData = [[NSMutableData alloc] initWithCapacity:expected];
self.response = response;
dispatch_async(dispatch_get_main_queue(), ^{
[[NSNotificationCenter defaultCenter] postNotificationName:SDWebImageDownloadReceiveResponseNotification object:self];
});
}
else {
NSUInteger code = [((NSHTTPURLResponse *)response) statusCode];
//This is the case when server returns '304 Not Modified'. It means that remote image is not changed.
//In case of 304 we need just cancel the operation and return cached image from the cache.
if (code == 304) {
[self cancelInternal];
} else {
[self.connection cancel];
}
dispatch_async(dispatch_get_main_queue(), ^{
[[NSNotificationCenter defaultCenter] postNotificationName:SDWebImageDownloadStopNotification object:self];
});
if (self.completedBlock) {
self.completedBlock(nil, nil, [NSError errorWithDomain:NSURLErrorDomain code:[((NSHTTPURLResponse *)response) statusCode] userInfo:nil], YES);
}
CFRunLoopStop(CFRunLoopGetCurrent());
[self done];
}
}