問題描述:
為了節(jié)約用戶流量以及提升用戶體驗(yàn),日常開發(fā)中手機(jī)端向服務(wù)端請求拿到圖片后會(huì)在手機(jī)端緩存該圖片,下次用戶在此瀏覽該圖片時(shí)直接從手機(jī)緩存中拿即可,無需再請求服務(wù)器從服務(wù)端再次獲取,但是這樣會(huì)造成一個(gè)問題
當(dāng)圖片的URL不發(fā)生改變,服務(wù)端單方面改變該URL對應(yīng)的圖片資源時(shí),手機(jī)端如何知曉及時(shí)再次向服務(wù)端請求最新圖片,而不是一直從緩存中獲取舊圖片。
解決方法:
要想解決這個(gè)問題,關(guān)鍵之處在我們手機(jī)端需要知曉服務(wù)端修改了圖片,其實(shí)HTTP協(xié)議本身就有對這個(gè)問題的解決機(jī)制。
http請求由三部分組成,分別是:請求行、消息報(bào)頭、請求正文。消息報(bào)頭就是我們?nèi)粘U埱蟮膆eader了
常用的消息報(bào)頭有很多,其中有一個(gè)叫Last-Modified
Last-Modified實(shí)體報(bào)頭域用于指示資源的最后修改日期和時(shí)間。通過這個(gè)標(biāo)識即可知曉服務(wù)端修改了圖片資源。
具體流程:
====第一次請求===
- 客戶端發(fā)起 HTTP GET 請求一個(gè)文件;
- 服務(wù)器處理請求,返回文件內(nèi)容和一堆Header,當(dāng)然包括Last-Modified(例如"2e681a-6-5d044840").狀態(tài)碼200
====第二次請求=== - 客戶端發(fā)起 HTTP GET 請求一個(gè)文件,注意這個(gè)時(shí)候客戶端同時(shí)發(fā)送一個(gè)If-Modified-Since頭,這個(gè)頭的內(nèi)容就是第一次請求時(shí)服務(wù)器返回的Last-Modified
- 服務(wù)器判斷發(fā)送過來的Last-Modified和計(jì)算出來的Last-Modified匹配,因此If-None-Match為False,不返回200,返回304,客戶端繼續(xù)使用
iOS日常開發(fā)中如何解決:
iOS日常開發(fā)中通常使用SDWebImage加載網(wǎng)絡(luò)圖片,那么在使用SDWebImage時(shí)如何解決以上問題。
- 使用SDWebImage時(shí),設(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) { }];
- appdelegate 中添加如下方法
//獲取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;
};
}```
#####做完以上兩步后就OK了,其他的事情SDWebImage都替我們做好了
SDWebImage具體實(shí)現(xiàn)可參閱以下代碼
```- (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];
}}```
參考鏈接:
[南楓小謹(jǐn)](http://www.code4app.com/blog-774076-312.html)
[kikikind](http://blog.csdn.net/kikikind/article/details/6266101)
[老李的地下室](http://www.cnblogs.com/li0803/archive/2008/11/03/1324746.html)