6

In iOS 7, I was able to set a shared URL cache to a subclass of NSURLCache and any UIWebViews I created would automatically use that shared cache for each request.

// Set the URL cache and leave it set permanently
ExampleURLCache *cache = [[ExampleURLCache alloc] init];
[NSURLCache setSharedURLCache:cache];

However, now in iOS 8 it doesn't seem like UIWebView pulls from the shared cache and cachedResponseForRequest never gets called.

Has anyone found documentation for this change, or a workaround?

phatmann
  • 18,161
  • 7
  • 61
  • 51
Jon Willis
  • 6,993
  • 4
  • 43
  • 51

1 Answers1

10

I had same problem today. It was ok on ios7 and broken on ios8.

The trick is to create your own cache as the first thing you do in didFinishLaunchingWithOptions.

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // IMPORTANT: call this line before anything else. Do not call [NSURLCache sharedCache] before this because that
    // creates a reference and then we can't create the new cache.
    NSURLCache *URLCache = [[NSURLCache alloc] initWithMemoryCapacity:4 * 1024 * 1024 diskCapacity:20 * 1024 * 1024 diskPath:nil];

    [NSURLCache setSharedURLCache:URLCache];

...

You can see this being done in other apps:

https://github.com/AFNetworking/AFNetworking/blob/master/Example/AppDelegate.m

This site, while old, has more info on why you shouldn't even call [NSURLCache sharedInstance] before the above code: http://inessential.com/2007/02/28/figured_it_the_heck_out

Yegor Razumovsky
  • 902
  • 2
  • 9
  • 26
  • 1
    Cool, I ended up fixing my specific issue by using another approach involving implementing a custom `NSURLProtocol`. If anyone wants to see the code just mention me here and I'll add it. – Jon Willis Sep 22 '14 at 19:09