-1

I am attempting to use NSURLCache so that my app will save JSON responses from a web server and not request it so much.

I have added Cache-Control:Max-Age=604800 to the response headers in the request.

I have added the following code my apps AppDelegate.m file:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{

    //set up the URL cache
    NSURLCache *URLCache = [[NSURLCache alloc] initWithMemoryCapacity:4 * 1024 * 1024
                                                         diskCapacity:20 * 1024 * 1024
                                                             diskPath:nil];
    [NSURLCache setSharedURLCache:URLCache];
}

And my request in the code looks like this:

NSString *myURLString = [NSString stringWithFormat:@"http://domain.com/api/?location=%@,%@&date=%@&method=%@", latitude, longitude, curDate, methodString];

NSLog(@"%@", myURLString);

NSURL *url = [NSURL URLWithString:myURLString];

NSData *jsonData = [NSData dataWithContentsOfURL:url];

I do not think this is working, because when running with instruments network profile I see a spike in network request each time the view is loaded and if I load the app then put the phone in plane mode no data loads (whereas I suspect it would use the cache).

Is this proof that no cache is being made/used? And, if so, does anyone have any ideas why not? And, if it's not proof, does anyone know how I can better test the caching?

Many thanks.

Mike Abdullah
  • 14,933
  • 2
  • 50
  • 75
samiles
  • 3,768
  • 12
  • 44
  • 71
  • 2
    `dataWithContentsOfURL:` is not meant to be used for remote URLs. That might be one cause of the problem. I would suggest you repeat your analysis with using `NSURLConnection`. – CouchDeveloper Jul 13 '13 at 12:21
  • Ah, that seems to be correct. I will replace with `NSURLConnection`. Thanks. – samiles Jul 13 '13 at 12:50
  • repost of http://stackoverflow.com/questions/17629214/how-to-test-check-use-of-nsurlcache – vikingosegundo Jul 14 '13 at 20:32

1 Answers1

0

+[NSData dataWithContentsOfURL:] makes absolutely no guarantees about what caching model it will follow. In practice at present, it deliberately ignores any cache.

You should instead use NSURLConnection which exposes proper caching controls.

Mike Abdullah
  • 14,933
  • 2
  • 50
  • 75