3

Do anyone have a sample code for implementing image caching using NSURLRequest, NSURLConnection and NSURLRequestReturnCacheDataElseLoad policy?

I am using the following code but seems like no caching is happening. All the time I am getting the image from the URL. Please tell me what's 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];
Abhinav
  • 37,684
  • 43
  • 191
  • 309
  • I also have this same problem. SDURLCache seems like the way to go, but the example code snippet that is provided in the documentation would ideally be more complete. I too am not observing any caching. When I load my view, I'm saying [self getImage]; I am assuming that by using SDURLCache, I don't have to do anything else. Or do I need to manually keep a "last modified" time, and then read from the sharedcache? If so, this saves me no time as I would have ended up implementing caching the manual way. – user798719 Mar 05 '12 at 21:40

2 Answers2

5

You may want to take a look at using SDURLCache: https://github.com/rs/SDURLCache

SDURLCache actually saves cache to disk, whereas NSURLCache doesn't. NSURLCache only caches in memory, so within your app session. See ReadMe at link which explains it in more detail.

Update: Looks like NSURLCache does cache to disk since iOS 5.x: http://petersteinberger.com/blog/2012/nsurlcache-uses-a-disk-cache-as-of-ios5/

Johan Kool
  • 15,637
  • 8
  • 64
  • 81
  • Not sure why I got a downvote. SDURLCache actually saves cache to disk, whereas NSURLCache doesn't. NSURLCache only caches in memory, so within your app session. (I've not confirmed this lately, but I'm quite certain thus is still the case.) – Johan Kool Jun 16 '11 at 17:04
  • The downvote was mine. I was looking for sample code using NSURLCache, just like the question states. SDURLCache isn't of any use to me, because I'm using Mono. But your comment perfectly explains why NSURLCache wouldn't help either way, so if you'd include that in your answer, I'd be happy to remove the downvote. Sorry I didn't comment earlier, I was a bit in a hurry at the time :) – Niels van der Rest Jun 20 '11 at 07:12
0

Or try https://github.com/rs/SDWebImage

Christian Loncle
  • 1,584
  • 3
  • 20
  • 30