Skip to content

Instantly share code, notes, and snippets.

@grantland
Created October 8, 2012 21:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save grantland/3855193 to your computer and use it in GitHub Desktop.
Save grantland/3855193 to your computer and use it in GitHub Desktop.
iOS NSURLCache bug

NSURLCache uses more than just the HTTP method and URL properties of NSURLRequest as the key for its cache. Therefore, it is possible for a request with method=GET and URL=X to return a miss with NSURLCache even though a NSCachedURLResponse was stored with method=GET and URL=X. These misses can be caused by non-http properties of NSURLRequest being different than the NSURLRequest used to store the NSCachedURLResponse.

We've seen the following show up as a miss:

NSURLCache * cache = //...    
NSURL *url = [NSURL URLWithString:@"http://example.com"];
NSURLRequestCachePolicy cachePolicy = NSURLRequestReturnCacheDataElseLoad;
NSURLRequest r1 = [NSURLRequest requestWithURL:url cachePolicy:cachePolicy timeoutInterval:30];
NSURLRequest r2 = [NSURLRequest requestWithURL:url cachePolicy:cachePolicy timeoutInterval:60];

[cache storeCachedResponse:/*response*/ forRequest:r1];
[cache cachedResponseForRequest:r1]; // HIT
[cache cachedResponseForRequest:r2]; // MISS

In order to get around this, you could write a key generator that canonicalizes NSURLRequests.

// HACK: NSURLCache is using some weird comparator to check the NSURLRequest key and breaks
// caching with UIWebView, so we are canonicalizing the key.
//
// We set a static timeout because different timeouts will result in a miss.
- (NSURLRequest *) generateKeyForRequest:(NSURLRequest *)request {
return [NSURLRequest requestWithURL:request.URL cachePolicy:request.cachePolicy timeoutInterval:60];
}
@xserver
Copy link

xserver commented Jan 14, 2014

NSURLRequests in object-C ? Not found !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment