SDWebImage 處理url鏈接中圖片更新問題

1. [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) {

}];

將options 設置為SDWebImageRefreshCached

2.appdelegate中didfinishlunch 中添加如下方法

-(void)sdWEbDownloaderRegister{

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;

};

}

加上以上代碼,sdwebimage在下載圖片前會將上次獲取的Etag、Last-Modified和本次需要下載的圖片的Etag、Last-Modified比對,若一致不會下載,若不一致說明有更新

Etag由服務器端生成,客戶端通過If-Match或者說If-None-Match這個條件判斷請求來驗證資源是否修改。常見的是使用If-None-Match.請求一個文件的流程可能如下:

====第一次請求===

1.客戶端發起 HTTP GET 請求一個文件;

2.服務器處理請求,返回文件內容和一堆Header,當然包括Etag(例如"2e681a-6-5d044840")(假設服務器支持Etag生成和已經開啟了Etag).狀態碼200

====第二次請求===

1.客戶端發起 HTTP GET 請求一個文件,注意這個時候客戶端同時發送一個If-None-Match頭,這個頭的內容就是第一次請求時服務器返回的Etag:2e681a-6-5d044840

2.服務器判斷發送過來的Etag和計算出來的Etag匹配,因此If-None-Match為False,不返回200,返回304,客戶端繼續使用

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

}

}

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容