糗事百科的閱讀方式跟微博很想,它是按時間線排布的。所以過幾分鐘刷新出來的內(nèi)容會是全新的。那這種情況其實做緩存的意義不是很大。這邊只是個實例而已,演示如何把圖片緩存到本地,在需要時優(yōu)先加載本地圖片,如果不存在再從網(wǎng)絡(luò)獲取,獲取成功后緩存起來。
所以整個流程是:
所有的操作均在UIImageView+Util這個UIImageView擴展類中實現(xiàn),具體代碼如下:
<pre>
-
(void)setImageWithURL:(NSString *)url placehold:(UIImage *)image
{
self.image = image;
UIImage * cacheImage = [self imageFromCacheWithURLString:url];
if (cacheImage) {
self.image = cacheImage;
return;
}if (url == nil) {
return;
}NSURL * requestURL = [NSURL URLWithString:url];
NSURLRequest * request = [NSURLRequest requestWithURL:requestURL];
NSOperationQueue * queue = [[NSOperationQueue alloc]init];[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if (connectionError == nil) { dispatch_async(dispatch_get_main_queue(), ^{ UIImage * netImage = [UIImage imageWithData:data]; self.image = netImage; [self saveImageToCache:netImage url:url]; }); } else { NSLog(@"%@", url); NSLog(@"加載圖片出問題了%@", connectionError.localizedDescription); }}];
}
</pre>
imageFromCacheWithURLString
<pre>
-
(UIImage *)imageFromCacheWithURLString:(NSString *)urlString
{
if (urlString == nil || [urlString isEqualToString:@""]) {
return nil;
}
NSString * md5String = [urlString md5];
NSFileManager * fileManager = [NSFileManager defaultManager];
NSError * error;
__block UIImage * cacheImage = nil;NSString * cacheImagePath = [self imageCachePath];
NSArray * cacheImages = [fileManager contentsOfDirectoryAtPath:cacheImagePath error:&error];if (error) {
NSLog(@"獲取緩存圖片目錄列表出錯:%@", error.localizedDescription);
return nil;
}
[cacheImages enumerateObjectsUsingBlock:^(NSString * fileName, NSUInteger idx, BOOL *stop) {
NSString * cacheImageItemPath = [cacheImagePath stringByAppendingPathComponent:fileName];
if ([md5String isEqualToString:fileName]) {
cacheImage = [UIImage imageWithContentsOfFile:cacheImageItemPath];
}
}];
return cacheImage;
}
</pre>
imageCachePath
<pre>- (NSString *)imageCachePath
{
NSString * documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES) objectAtIndex:0];
NSString * cacheImagePath = [documentsDirectory stringByAppendingPathComponent:@"_imageCache"];
NSFileManager * fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:cacheImagePath] == NO) {
[fileManager createDirectoryAtPath:cacheImagePath withIntermediateDirectories:YES attributes:nil error:nil];
}
return cacheImagePath;
}</pre>
saveImageToCache
<pre>- (void)saveImageToCache:(UIImage *)image url:(NSString *)url
{
NSString * cacheImagePath = [self imageCachePath];
NSString * md5FileName = [url md5];
NSString * imageCachePath = [cacheImagePath stringByAppendingPathComponent:md5FileName];
[UIImagePNGRepresentation(image) writeToFile:imageCachePath atomically:YES];
}</pre>
需要注意一點的是MD5的使用。在判斷緩存文件是否是我們需要的時候,我們使用url的md5值來做唯一性比較,這樣會比較準(zhǔn)確,但是會浪費一些時間開銷。