ios - 缓存下载的数据

标签 ios objective-c caching uicollectionview

我正在使用 Collection View 在每个单元格中显示产品数据。每次用户刷新 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 设置内存和磁盘缓存:

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

关于ios - 缓存下载的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33265927/

相关文章:

iphone - 将 Controller 推送到 UINavigationController 在 iPad 上可以工作,但在 iPhone 上不行

ios - 在自定义 NSURLProtocol 上使用 AVURLAsset

c++ - C++ 中的动态绑定(bind)示例

ios - 如何在 IOS 中隐藏 UILabel 中的文本

ios - 如何在 iOS 8.1 中转换 "Tue, 14 Jul 2015 15:00:00 +0000"

iphone - 生成文档缩略图

ubuntu - Varnish 似乎在工作,但 max-age=0

java - Hibernate - maxElementsOnDisk 从 EHCache 到 TreeCache

android - 如何为 webview 启用 expires-header 缓存

ios - $(APP_BUNDLE_ID) 和 $(APP_NAME) 不起作用