I have seen several posts for this question and I cant figure out how to get this working. For example, this post NSCachedURLResponse returns object, but UIWebView does not interprets content
suggests that we subclass and override cachedResponseForRequest
and modify the NSURLRequest
before returning a cached response (not sure why this needs to be done).
This is the code i have in my NSURLCache
subclass:
- (NSCachedURLResponse *)cachedResponseForRequest:(NSURLRequest *)request {
NSCachedURLResponse *resp = [super cachedResponseForRequest:request];
if (resp != nil && resp.data.length > 0) {
NSDictionary *headers = @{@"Access-Control-Allow-Origin" : @"*", @"Access-Control-Allow-Headers" : @"Content-Type"};
NSHTTPURLResponse *urlresponse = [[NSHTTPURLResponse alloc] initWithURL:request.URL statusCode:200 HTTPVersion:@"1.1" headerFields:headers];
NSCachedURLResponse *cachedResponse = [[NSCachedURLResponse alloc] initWithResponse:urlresponse data:resp.data];
return cachedResponse;
} else {
return nil;
}
}
Now when i load the request via the webview and I'm offline, the delegate didFailLoadWithError
gets called (it was not able to load), but before that delegate method is called, my cachedResponseForRequest
method gets called and the cached response has some html however my didFailLoadWithError
method still gets called. So my question is, should the webViewDidFinishLoad
should get called if we return the cached response from the NSURLCache
, if not how do i make this work?
I have this in my didFinishLaunchingWithOptions
:
NSUInteger cacheSizeMemory = 500*1024*1024; // 500 MB
NSUInteger cacheSizeDisk = 500*1024*1024; // 500 MB
NSURLCache *sharedCache = [[CustomCache alloc] initWithMemoryCapacity:cacheSizeMemory diskCapacity:cacheSizeDisk diskPath:@"nsurlcache"];
[NSURLCache setSharedURLCache:sharedCache];
This is the flow i want working:
- Launch the app.
- Hit some url (lets say slickdeals.net)
- Go offline kill the application
- Launch the application
UIWebView
attempts to hit url but device is offline and a returned cached response is returned.- We display cached response.
Any thoughts on what needs to change in my code is appreciated!