美文网首页
OC:SDWebImage不能及时更新网络图片的问题

OC:SDWebImage不能及时更新网络图片的问题

作者: 春暖花已开 | 来源:发表于2019-04-03 09:30 被阅读0次
说明
首次发布 2019年04月03日
最近更新 2019年04月03日

背景: SDWebImage 是基于 URL 作为 key 来实现缓存功能,一般情况下,服务器在变更图片后,都需要同步修改URL地址。对于极少情况下,图片改变却未改变地址的情况,客户端就拿不到最新的图片了。

步骤:

步骤一:

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;
};

步骤二: 在设置图片的地方处理,将 Options 设为 SDWebImageRefreshCached

NSURL *imgURL = [NSURL URLWithString:urlStr];
[self.imgView sd_setImageWithURL:imgURL placeholderImage:nil options:SDWebImageRefreshCached];

关于 If-Modified-Since 的说明:
If-Modified-Since 是一个条件式请求首部,服务器只在所请求的资源在给定的日期时间之后对内容进行过修改的情况下才会将资源返回,状态码为 200 。如果请求的资源从那时起未经修改,那么返回一个不带有消息主体的 304 响应,而在 Last-Modified 首部中会带有上次修改时间。 不同于 If-Unmodified-SinceIf-Modified-Since 只可以用在 GETHEAD 请求中。


参考自 Handy's 的博文,在此表示衷心的感谢。

相关文章

网友评论

      本文标题:OC:SDWebImage不能及时更新网络图片的问题

      本文链接:https://www.haomeiwen.com/subject/fkxabqtx.html