突然看到這兩篇文章SDWebImage 處理url鏈接中圖片更新問題,URL不變,服務(wù)端圖片更新,客戶端同步更新問題。想起來曾經(jīng)面試問到過的問題,到時候回答時候說給每個圖片鏈接加個標(biāo)識,服務(wù)端改變圖片的時候改變標(biāo)識,清除前端緩存,重新下載圖片。但是這明顯不合理,圖片會改變很多次,標(biāo)識的話那的多少標(biāo)識?看了這兩篇文章才知道HTTP協(xié)議本身就有對這個問題的解決機(jī)制。
平時我們?yōu)榱斯?jié)約流量以及提升用戶體驗(yàn),從后端請求的圖片都會在手機(jī)端進(jìn)行緩存,這是毫無質(zhì)疑的。但是當(dāng)圖片的URL不發(fā)生改變,服務(wù)端單方面改變該URL對應(yīng)的圖片資源時,手機(jī)端如何知曉及時再次向服務(wù)端請求最新圖片,而不是一直從緩存中獲取舊圖片。
首先我們要知道http請求由三部分組成,分別是:請求行、消息報(bào)頭、請求正文。消息報(bào)頭就是我們?nèi)粘U埱蟮膆eader了
常用的消息報(bào)頭有很多,其中有一個叫Last-Modified
Last-Modified實(shí)體報(bào)頭域用于指示資源的最后修改日期和時間。通過這個標(biāo)識即可知曉服務(wù)端修改了圖片資源。
SDWebImage在下載圖片前會將上次獲取的Etag、Last-Modified和本次需要下載的圖片的Etag、Last-Modified比對,若一致不會下載,若不一致說明有更新
Etag由服務(wù)器端生成,客戶端通過If-Match或者說If-None-Match這個條件判斷請求來驗(yàn)證資源是否修改。常見的是使用If-None-Match.請求一個文件的流程可能如下:
====第一次請求===
1.客戶端發(fā)起 HTTP GET 請求一個文件;
2.服務(wù)器處理請求,返回文件內(nèi)容和一堆Header,當(dāng)然包括Etag(例如"2e681a-6-5d044840")(假設(shè)服務(wù)器支持Etag生成和已經(jīng)開啟了Etag).狀態(tài)碼200
====第二次請求===
1.客戶端發(fā)起 HTTP GET 請求一個文件,注意這個時候客戶端同時發(fā)送一個If-None-Match頭,這個頭的內(nèi)容就是第一次請求時服務(wù)器返回的Etag:2e681a-6-5d044840
2.服務(wù)器判斷發(fā)送過來的Etag和計(jì)算出來的Etag匹配,因此If-None-Match為False,不返回200,返回304,客戶端繼續(xù)使用。
大體流程就是這個。
然后我們分兩步去做
使用SDWebImage時,設(shè)置下載選項(xiàng)options:為SDWebImageRefreshCached
代碼如下:
[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) { }];
2.需要在 AppDelegate的里面-(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 這個方法內(nèi)加入以下代碼。
//獲取SDWebImage的下載對象,所有圖片的下載都是此對象完成的 SDWebImageDownloader *imgDownloader=SDWebImageManager.sharedManager.imageDownloader;
imgDownloader.headersFilter = ^NSDictionary *(NSURL *url, NSDictionary *headers) {
//下載圖片成功后的回調(diào)
NSFileManager *fm = [[NSFileManager alloc] init];
NSString *imgKey = [SDWebImageManager.sharedManager cacheKeyForURL:url];
NSString *imgPath = [SDWebImageManager.sharedManager.imageCache defaultCachePathForKey:imgKey];
//獲取當(dāng)前路徑圖片服務(wù)端返回的請求頭相關(guān)信息
NSDictionary *fileAttr = [fm attributesOfItemAtPath:imgPath error:nil];
NSMutableDictionary *mutableHeaders = [headers mutableCopy];
NSDate *lastModifiedDate = nil;
//大于0則表示請求圖片成功
if (fileAttr.count > 0) {
if (fileAttr.count > 0) {
//如果請求成功,則手機(jī)端取出服務(wù)端Last-Modified信息
lastModifiedDate = (NSDate *)fileAttr[NSFileModificationDate];
}
}
//格式化Last-Modified
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 : @"";
//設(shè)置SDWebImage的請求頭If-Modified-Since
[mutableHeaders setValue:lastModifiedStr forKey:@"If-Modified-Since"];
return mutableHeaders;
};
其他的交給SDWebImage去做了,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];
}}
其實(shí)這種情況在開發(fā)中還是很少見的,一般都是后端改變的圖片的資源,圖片的URL也會去該改變,但是遇到問題了就得解決問題,這是開發(fā)者必備的。希望多大家有幫助!
參考:
SDWebImage 處理url鏈接中圖片更新問題
URL不變,服務(wù)端圖片更新,客戶端同步更新問題