Use NSURLConnection cache when device is offline

1.2k views Asked by At

In an NSOperation subclass, I am using the following code to download an xml-file from our server, and then later parse it:

NSURLRequest * request = [NSURLRequest requestWithURL:[NSURL URLWithString:url] 
                                          cachePolicy:NSURLRequestUseProtocolCachePolicy
                                      timeoutInterval:15];
NSData * receivedData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

The second time I make the same request, the server returns a HTTP 304, and the cached response data is stored in receivedData. So far so good.

My question: is it possible to get this same cached response when the device is offline?

1

There are 1 answers

1
El Horrible On

NSURLCache does not support disk caching. You can simply store it manually or use this: https://github.com/steipete/SDURLCache

It is very simple cache that does its job...very simple usage, only one class...It supports etags also.



    // Do this only once in your app...
    SDURLCache *urlCache = [[SDURLCache alloc] initWithMemoryCapacity:1024*1024   // 1MB mem cache
                                                         diskCapacity:1024*1024*5 // 5MB disk cache
                                                             diskPath:[SDURLCache defaultCachePath]];
    [NSURLCache setSharedURLCache:urlCache];
    [urlCache release];