UIImageView + AFNetworking并保存图像

时间:2014-01-30 07:40:13

标签: ios objective-c caching afnetworking

我需要将图像设置为我的imageViews。并且有很多图像(我认为它将接近200mb)。我需要保存所有内容,以便在本地使用app而无需连接互联网。使用类别UIImageView+AFNetworking非常容易,但我不明白它是如何保存的以及在哪里?

所以订阅方法here ,您可以看到它使用NSURLCacheStorageAllowed的缓存策略。所以图像保存在磁盘上的缓存文件夹中,对吗?这一切都没问题,但这个存储的限制是什么?我是否需要实现下一个代码:

 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
  //another code...
  NSURLCache *URLCache = [[NSURLCache alloc] initWithMemoryCapacity:4 * 1024 * 1024 
                                                   diskCapacity:200 * 1024 * 1024 
                                                       diskPath:nil];
  [NSURLCache setSharedURLCache:URLCache];
  return YES;
}

所以NSURLCacheStorageAllowedstoragePolicy的{​​{1}}一样返回NSCachedURLResponse。所以我理解我不得实现上面编写的代码。

如果我要使用UIImageView+AFNetworking类别,我的所有图片都会保存在本地缓存中吗?

2 个答案:

答案 0 :(得分:3)

正如您所发现的,UIImageView + AFNetworking依赖于基础URL加载系统来将数据缓存到磁盘。 diskCapacity将确定您的应用一次需要多少存储空间。这也将依赖于服务器在处理图像时指定适当的Cache-Control标头 - 在某些情况下,如果缓存时间太短,NSURLCache将根本不存储它。

要在客户端更好地控制磁盘缓存,可以查看SDWebImage

SDWebImage具有异步图像下载功能,可以对缓存进行大量控制 - 哪些图像可以缓存,在磁盘或内存中保存多长时间等。如果需要保证图像存储特定的时间,UIImageView + AFNetworking可能无法为您提供所需的控制权,您应该探索这种替代方案。

答案 1 :(得分:0)

当我需要在tableView中显示图像时,我已经做了同样的想法,首先我检查图像是否在本地可用然后我下载图像并保存它像这样

if (userBasicInfo.userImage == nil) {
            __weak LGMessageBoxCell *weakCell = cell;
            [cell.userImage setImageWithURLRequest:[[NSURLRequest alloc] initWithURL:[NSURL URLWithString:userBasicInfo.imageUrl]]
                                  placeholderImage:[UIImage imageNamed:@"facebook-no-user.png"]
                                           success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image){
                                               weakCell.userImage.image = image;
                                               [weakCell setNeedsLayout];

                                               [MagicalRecord saveWithBlock:^(NSManagedObjectContext *localContext) {
                                                   UserBasicInfo* userBasicInfo = [[UserBasicInfo findByAttribute:@"userId" withValue:@(chatUser) inContext:localContext] objectAtIndex:0];
                                                   userBasicInfo.userImage = UIImagePNGRepresentation(image);
                                               } completion:^(BOOL success, NSError *error) {
                                                   NSLog(@"%@",[error localizedDescription]);
                                               }];

                                           }
                                           failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error){
                                           }];
        } else {
            cell.userImage.image = [UIImage imageWithData:userBasicInfo.userImage];
        }