禁用UIWebView DiskImageCache

时间:2013-05-13 14:54:25

标签: ios objective-c caching uiwebview docx

加载包含图像的文档(例如 Microsoft Word docx 文件)时,无论缓存策略如何,UIWebView在收到内存警告时都会缓存图像。

以下是一个示例代码段:

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];

在这些情况下,如果发生内存警告,则会在应用的 tmp 目录中创建一个新文件夹,通常名为 DiskImageCache-random_suffix ,并且所有图片都在打开的文件保存在这里。

UIWebView 加载新请求后,如果我调用

[sharedCache removeAllCachedResponses];

删除这些临时图像。

防止缓存图像的唯一方法是调用

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

但这意味着使用私有API。

是否有“Apple友好”的方式来实现这一目标?

1 个答案:

答案 0 :(得分:6)

在查看WebKit“未记录的”首选项后,我发现了它。通过以下设置,可以在应用程序的整个生命周期内禁用DiskImageCache:

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