0

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:

  1. Launch the app.
  2. Hit some url (lets say slickdeals.net)
  3. Go offline kill the application
  4. Launch the application
  5. UIWebView attempts to hit url but device is offline and a returned cached response is returned.
  6. We display cached response.

Any thoughts on what needs to change in my code is appreciated!

Community
  • 1
  • 1
Rafthecalf
  • 461
  • 6
  • 20

1 Answers1

0

NSURLCache is designed for HTTP conform caching, and often behaves unexpectly. You must wrote your own cache for your use case, and implement a custom NSURLProtocol to use it. The protocol put the responses into your cache, and provides them from cache when offline. Rob Napier wrotes an excellent article about this.

clemens
  • 16,716
  • 11
  • 50
  • 65