【问题标题】:How to store image data in cache如何将图像数据存储在缓存中
【发布时间】:2014-07-07 03:21:03
【问题描述】:

我有一个来自 url 的可变字典存储图像数组。那么如何将图像存储在应用程序缓存中,我可以在没有互联网连接时查看图像。

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    static NSString * CellIndentifier=@"CustomCell";
    CustomCell *cell = (CustomCell*)[collectionView dequeueReusableCellWithReuseIdentifier:CellIndentifier forIndexPath:indexPath];
    NSDictionary *dictVideo = [self.videoList objectAtIndex:indexPath.row];
    [cell.indicator startAnimating];
    //set title
    NSString *titleVideo = [dictVideo objectForKey:@"Title"];
    [cell.myLabel setText:titleVideo];
    // set image url
    NSString *urlVideo = [dictVideo objectForKey:@"Url"];
    NSURL *url = [NSURL URLWithString:urlVideo];
    cell.imageView.image = nil;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSData *data = [NSData dataWithContentsOfURL:url];
        UIImage * img = [[UIImage alloc]initWithData:data];
        dispatch_sync(dispatch_get_main_queue(), ^{
            NSLog(@"%ld  %@  %@",(long)indexPath.row,titleVideo,url);
                [cell.imageView setImage: img];
                [cell.indicator stopAnimating];
        });
          });
           return cell;
    }

【问题讨论】:

  • 定义cache。你本地的sqlite,documents文件夹?您有几个选择,因为您已经拥有原始数据。示例:[[NSFileManager defaultManager] createFileAtPath:path contents:data attributes:nil];
  • 我想将我从 Internet 下载的图像存储到文档中的 Caches 文件夹中以更快地加载图像
  • 我这里就这样回答一个问题,包括使用NSCache缓存图片数据...stackoverflow.com/questions/15799432/…
  • @TimeToLearn 如果你想在这里缓存图片是非常好的库SDWebImage

标签: ios objective-c caching


【解决方案1】:

你可以像 Umar Farooq 所说的那样使用 SDWebImage 库,它同时支持 iOS 6 和 7 然后您可以在 .m 文件中使用以下代码

#import "UIImageView+WebCache.h"
 UIImage *Noimg = [UIImage imageNamed:@"noimg.png"];
     [cell.PlaceImg  setImageWithURL:[NSURL URLWithString:strImgname]  placeholderImage:Noimg];

这里的Noimg是占位符图像,当图像位置没有找到图像时,它会自动由库管理

【讨论】:

    【解决方案2】:

    NSURLCache 已经为你做到了。您的应用程序已经有一个可能没有磁盘持久性的隐式 NSURLCache,因此您需要显式设置它:

    NSURLCache *cache = [[NSURLCache alloc]initWithMemoryCapacity:(5 * 1024 * 1024) diskCapacity:(10 * 1024 *1024) diskPath:@"NSURLCache.db"];
    [NSURLCache setSharedURLCache:cache];
    

    从那时起,URL 加载系统会将数据存储在内存和磁盘中。这将允许它在没有连接时可用。您继续像往常一样发出请求,当从缓存中提供服务时,它们返回的速度要快得多。

    如果你想修改这个行为,你应该修改你的 NSURLRequest 使用的缓存策略(例如,NSURLRequestReturnCacheDataElseLoad 或 NSURLRequestReturnCacheDataDontLoad)。不幸的是,您使用的是dataWithContentsOfURL:,它没有提供这样做的机会。使用 NSURLSessionTask 或 NSURLConnection 可以让你这样做。

    请记住,服务器确实会告诉客户端响应的有效时间,并且默认缓存策略确实会遵守这一点。

    【讨论】:

      猜你喜欢
      • 2012-01-16
      • 1970-01-01
      • 1970-01-01
      • 2020-04-16
      • 2012-08-05
      • 2019-05-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多