NSURLCache not caching

2.9k views Asked by At

So I have subclassed NSURLCache and every time I call loadHTMLFromString: it calls storeCachedRequest:forRequest: and then cachedResponseForRequest:. Here's what I have:

- (NSCachedURLResponse *)cachedResponseForRequest:(NSURLRequest *)request
{
    NSString *pathString = [[request URL] absoluteString];

    NSCachedURLResponse * response = [super cachedResponseForRequest:request];
    if (response != nil)
        return response;
    else {
        NSString* myString= @"testing";

        NSData* data=[myString dataUsingEncoding: NSASCIIStringEncoding ];

        //
        // Create the cacheable response
        //
        NSURLResponse *response =
        [[[NSURLResponse alloc]
          initWithURL:[request URL]
          MIMEType:[self mimeTypeForPath:pathString]
          expectedContentLength:[data length]
          textEncodingName:nil]
         autorelease];
        NSCachedURLResponse * cachedResponse =
        [[[NSCachedURLResponse alloc] initWithResponse:response data:data] autorelease];

        [self storeCachedResponse:cachedResponse forRequest:request] ;

        //NSLog(@"DEFAULT CACHE WITH URL %@", [[request URL] absoluteString]);
        return [super cachedResponseForRequest:request];
    }

    return nil;
}

- (void)storeCachedResponse:(NSCachedURLResponse *)cachedResponse forRequest:(NSURLRequest *)request
{
    [super storeCachedResponse:cachedResponse forRequest:request];

    NSLog(@"STORE CACHED RESPONSE WITH URL %@", [[request URL] absoluteString]);
}

The issue is that when I call cachedResponseForRequest: right after it is saved, the response is always nil. Why is this?

I had:

NSURLRequest * req = [NSURLRequest requestWithURL:[NSURL URLWithString:self.imageSource_]];
NSCachedURLResponse * response = [[NSURLCache sharedURLCache] cachedResponseForRequest:req];

if (response == nil)
    NSLog(@"RESPONSE IS NIL");
else {
    NSString* theString = [[NSString alloc] initWithData:response.data encoding:NSASCIIStringEncoding];
    NSLog(@"RESPONSE IS NOT NIL %@", theString);
}

and it always prints response is nil. The url string is the same as it was when it storeCachedResponse. For some reason it is not caching. I've set the cache size to some amount of size.

2

There are 2 answers

5
Johan Kool On

Not 100% sure, but I think you need to use the NSURLResponse that got returned by your NSURLConnection instead of creating your own. My suspicion is that if you just create a NSURLResponse it doesn't have any headers set for the caching, and so NSURLCache assumes it should cache this particular result.

0
E. Rivera On

The default NSURLCache seems to be pretty random when choosing what to cache or not. Your best bet may be to subclass it and handle caching of the files you mind directly in cachedResponseForRequest: and leaving the rest for super.