Implement NSURLRequest, NSURLConnection, and NSURLRequestReturnCacheDataElseLoad

Does anyone have sample code to implement image caching using NSURLRequest, NSURLConnection and NSURLRequestReturnCacheDataElseLoad policy?

I am using the following code, but it looks like caching is not happening. All the time I get the image from the URL. Please tell me what is wrong here:

NSMutableURLRequest *req=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://i54.tinypic.com/10pd2jk.png"]];
    NSData *data=[NSURLConnection sendSynchronousRequest:req returningResponse:nil error:nil];
    NSLog(@"Received %d bytes", [data length]);
    [req setCachePolicy:NSURLRequestReturnCacheDataElseLoad];
    data=[NSURLConnection sendSynchronousRequest:req returningResponse:nil error:nil];
    NSLog(@"Received %d bytes", [data length]);
    [[NSURLCache sharedURLCache] setMemoryCapacity:1024*1024*10];


    UIImage *myImage = [UIImage imageWithData:data];
    UIImageView *sd = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10, 50, 50)];
    sd.image = myImage;
    [self.view addSubview:sd];
+3
source share
2 answers

You can take a look at using SDURLCache: https://github.com/rs/SDURLCache

SDURLCache actually saves the cache to disk, while NSURLCache does not. NSURLCache is cached only in memory, therefore in your application session. See ReadMe for a link that explains this in more detail.

: , NSURLCache iOS 5.x: http://petersteinberger.com/blog/2012/nsurlcache-uses-a-disk-cache-as-of-ios5/

+5

Source: https://habr.com/ru/post/1787019/


All Articles