Disable UIWebView DiskImageCache

2019-04-09 17:27发布

问题:

When loading documents that contain images (such as a Microsoft Word docx file), the UIWebView will always cache the images when it receives a memory warning regardless of the cache policy.

Following, there's a sample code snippet:

NSURLCache *sharedCache = [[NSURLCache alloc] initWithMemoryCapacity:1024 * 1024
                                              diskCapacity:0
                                              diskPath:[NSTemporaryDirectory() stringByAppendingPathComponent:@"URLCache"]];
[NSURLCache setSharedURLCache:sharedCache];

NSURLRequest* req = [NSURLRequest requestWithURL:
                    [NSURL URLWithString:@"http://www.its.swinburne.edu.au/about/projects/templates/TechnicalSpecificationTemplatev1.1-[ProjectName]-[ver]-[YYYYMMDD].docx"] 
                    cachePolicy:NSURLRequestReloadIgnoringCacheData 
                    timeoutInterval:10];

Under these circumstances, if a memory warning occurs, a new folder is created in the tmp directory of the app, usually named DiskImageCache-random_suffix and all the images in the opened document are saved here.

After the UIWebView loads a new request, if I call

[sharedCache removeAllCachedResponses];

these temporary images are removed.

The only way to prevent caching the images is to call

[NSClassFromString(@"WebCache") performSelector:@selector(setDisabled:) withObject:[NSNumber numberWithBool:YES]];

but this means using private API.

Is there an "Apple friendly" way to achieve this ?

回答1:

I figured it out after looking into the WebKit "undocumented" preferences. With the following setting, it is possible to disable DiskImageCache for the entire lifetime of the application:

[[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"WebKitDiskImageCacheEnabled"];
[[NSUserDefaults standardUserDefaults] synchronize];