問題描述:
為了節約用戶流量以及提升用戶體驗,日常開發中手機端向服務端請求拿到圖片后會在手機端緩存該圖片,下次用戶在此瀏覽該圖片時直接從手機緩存中拿即可,無需再請求服務器從服務端再次獲取,但是這樣會造成一個問題
當圖片的URL不發生改變,服務端單方面改變該URL對應的圖片資源時,手機端如何知曉及時再次向服務端請求最新圖片,而不是一直從緩存中獲取舊圖片。
解決方法:
要想解決這個問題,關鍵之處在我們手機端需要知曉服務端修改了圖片,其實HTTP協議本身就有對這個問題的解決機制。
http請求由三部分組成,分別是:請求行、消息報頭、請求正文。消息報頭就是我們日常請求的header了
常用的消息報頭有很多,其中有一個叫Last-Modified
Last-Modified實體報頭域用于指示資源的最后修改日期和時間。通過這個標識即可知曉服務端修改了圖片資源。
具體流程:
====第一次請求===
- 客戶端發起 HTTP GET 請求一個文件;
- 服務器處理請求,返回文件內容和一堆Header,當然包括Last-Modified(例如"2e681a-6-5d044840").狀態碼200
====第二次請求=== - 客戶端發起 HTTP GET 請求一個文件,注意這個時候客戶端同時發送一個If-Modified-Since頭,這個頭的內容就是第一次請求時服務器返回的Last-Modified
- 服務器判斷發送過來的Last-Modified和計算出來的Last-Modified匹配,因此If-None-Match為False,不返回200,返回304,客戶端繼續使用
iOS日常開發中如何解決:
iOS日常開發中通常使用SDWebImage加載網絡圖片,那么在使用SDWebImage時如何解決以上問題。
- 使用SDWebImage時,設置下載選項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) {
//下載圖片成功后的回調
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;
//大于0則表示請求圖片成功
if (fileAttr.count > 0) {
if (fileAttr.count > 0) {
//如果請求成功,則手機端取出服務端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 : @"";
//設置SDWebImage的請求頭If-Modified-Since
[mutableHeaders setValue:lastModifiedStr forKey:@"If-Modified-Since"];
return mutableHeaders;
};
}```
#####做完以上兩步后就OK了,其他的事情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];
}}```
參考鏈接:
[南楓小謹](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)