简体   繁体   English

缓存下载的数据

[英]Caching the downloaded data

I am using collection View to display the product data in each cell. 我正在使用集合视图在每个单元格中显示产品数据。 Each time when user refreshes collectionview , it fetches data from the server again. 每次用户刷新collectionview ,它都会再次从服务器获取数据。

I need to know is there a caching mechanism available which caches downloaded images. 我需要知道是否有可用的缓存机制来缓存下载的图像。 I want to download only recently updated products which are not cached. 我只想下载未缓存的最近更新的产品。

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

Use NSURLCache to setup memory and disk cache like this: 使用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];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM