Joke基本项目构建3 添加缓存图片

糗事百科的阅读方式跟微博很想,它是按时间线排布的。所以过几分钟刷新出来的内容会是全新的。那这种情况其实做缓存的意义不是很大。这边只是个实例而已,演示如何把图片缓存到本地,在需要时优先加载本地图片,如果不存在再从网络获取,获取成功后缓存起来。

所以整个流程是:

Joke基本项目构建3 添加缓存图片_第1张图片

所有的操作均在UIImageView+Util这个UIImageView扩展类中实现,具体代码如下:

  • (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);
      }
    

    }];
    }

imageFromCacheWithURLString

  • (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;

}

imageCachePath

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

}

saveImageToCache

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

}

需要注意一点的是MD5的使用。在判断缓存文件是否是我们需要的时候,我们使用url的md5值来做唯一性比较,这样会比较准确,但是会浪费一些时间开销。

你可能感兴趣的:(Joke基本项目构建3 添加缓存图片)