URL不变,服务端图片更新,客户端同步更新问题

问题描述:

为了节约用户流量以及提升用户体验,日常开发中手机端向服务端请求拿到图片后会在手机端缓存该图片,下次用户在此浏览该图片时直接从手机缓存中拿即可,无需再请求服务器从服务端再次获取,但是这样会造成一个问题

当图片的URL不发生改变,服务端单方面改变该URL对应的图片资源时,手机端如何知晓及时再次向服务端请求最新图片,而不是一直从缓存中获取旧图片。

解决方法:

要想解决这个问题,关键之处在我们手机端需要知晓服务端修改了图片,其实HTTP协议本身就有对这个问题的解决机制。
http请求由三部分组成,分别是:请求行、消息报头、请求正文。消息报头就是我们日常请求的header了
常用的消息报头有很多,其中有一个叫Last-Modified
Last-Modified实体报头域用于指示资源的最后修改日期和时间。通过这个标识即可知晓服务端修改了图片资源。

具体流程:

====第一次请求===

  1. 客户端发起 HTTP GET 请求一个文件;
  2. 服务器处理请求,返回文件内容和一堆Header,当然包括Last-Modified(例如"2e681a-6-5d044840").状态码200
    ====第二次请求===
  3. 客户端发起 HTTP GET 请求一个文件,注意这个时候客户端同时发送一个If-Modified-Since头,这个头的内容就是第一次请求时服务器返回的Last-Modified
  4. 服务器判断发送过来的Last-Modified和计算出来的Last-Modified匹配,因此If-None-Match为False,不返回200,返回304,客户端继续使用

iOS日常开发中如何解决:

iOS日常开发中通常使用SDWebImage加载网络图片,那么在使用SDWebImage时如何解决以上问题。

  1. 使用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) { }];
  2. 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)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容