Search code examples
iphonecachingnsurlconnectiondisknsurlrequest

Does disk caching with NSURLRequest and NSURLConnection actually work on the iPhone?


I have a UITableView whose cells contain custom ImageViews that asynchronously load the images from the internet. To load those images I use NSURLRequest and NSURLConnection which works fine. The only problem is that the images are not cached and therefore are downloaded every time they are used. I tried to set the cachePolicy of the NSURLRequest to "NSURLRequestReturnCacheDataElseLoad" with no effect.

It seems from the last answer on link that disk caching is not supported with NSURLRequest on the iPhone. Is this correct?

If it should actually work, I'd be interested to know what could be the reason that it doesn't work in my case.

Here's the code:

NSURLRequest* request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://myurl"] cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:60.0];


connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];

Solution

  • I think it should work. If it does not then it could mean that the web server is actually serving content that is not cacheable. For example because it is not setting the right headers.

    If you can post a link to one of the images then we can take a close look.

    HTTP/1.1 200 OK
    Date: Mon, 01 Mar 2010 12:40:46 GMT
    Server: Apache
    Last-Modified: Mon, 01 Mar 2010 09:33:29 GMT
    ETag: "25e8dd2-11a6-480b9f1178c40"
    Accept-Ranges: bytes
    Content-Length: 4518
    Keep-Alive: timeout=15, max=100
    Connection: Keep-Alive
    Content-Type: image/png
    

    This is what one of your images returns as headers. I don't see a Expires or Cache-Control header, so that may be why they are not cached. I think as far as WebKit is concerned, this is dynamic content that should be reloaded every time.