【问题标题】:Caching the downloaded data缓存下载的数据
【发布时间】:2015-10-22 02:00:46
【问题描述】:

我正在使用集合视图来显示每个单元格中的产品数据。每次用户刷新collectionview时,都会再次从服务器获取数据。

我需要知道是否有可用的缓存机制来缓存下载的图像。我只想下载未缓存的最近更新的产品。

NSURL *url = [NSURL URLWithString:@"http://www.myURL/productAll.php"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
    NSError *myError = nil;
    id res = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&myError];        
    items = [[NSMutableArray alloc] init];
    for (int i=0; i<[res count]; i++) {
        NSString *arrayResult = [[res objectAtIndex:i]objectForKey:@"image"];            
        NSData *data = [[NSData alloc] initWithBase64EncodedString:arrayResult options:NSDataBase64DecodingIgnoreUnknownCharacters];
        UIImage *captcha_image = [[UIImage alloc] initWithData:data];
        [items addObject:captcha_image];
    }
    [collectionView reloadData];
}];

【问题讨论】:

  • 尝试使用NSURLCache
  • 能否请您举个例子说明一下?
  • 在下面查看我的答案,只是一个简单的例子(未经测试),但我在几个应用程序中使用了类似的东西
  • 我看过你的代码,非常感谢。我想知道你怎么知道哪个产品被缓存了?我赞成你的回答。
  • 看看`-cachedResponseForRequest:`

标签: ios objective-c caching uicollectionview


【解决方案1】:

使用 NSURLCache 来设置内存和磁盘缓存,如下所示:

int cacheSizeMemory = xxxxx; //in memory cache
int cacheSizeDisk = xxxxx; //disk cache
NSURLCache *sharedCache = [[NSURLCache alloc] initWithMemoryCapacity:cacheSizeMemory diskCapacity:cacheSizeDisk diskPath:@"nsurlcache"];
[NSURLCache setSharedURLCache:sharedCache];

【讨论】:

    猜你喜欢
    • 2013-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-07
    • 1970-01-01
    • 2017-04-10
    • 2010-10-06
    • 2020-05-27
    相关资源
    最近更新 更多