糗事百科的阅读方式跟微博很想,它是按时间线排布的。所以过几分钟刷新出来的内容会是全新的。那这种情况其实做缓存的意义不是很大。这边只是个实例而已,演示如何把图片缓存到本地,在需要时优先加载本地图片,如果不存在再从网络获取,获取成功后缓存起来。
所以整个流程是:
所有的操作均在UIImageView+Util
这个UIImageView扩展类中实现,具体代码如下:
<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值来做唯一性比较,这样会比较准确,但是会浪费一些时间开销。