Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shared NSURLCache and UIWebView on iOS 8

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?

like image 734
Jon Willis Avatar asked Sep 15 '14 17:09

Jon Willis


1 Answers

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

like image 200
Yegor Razumovsky Avatar answered Nov 20 '22 06:11

Yegor Razumovsky