如何在Cocoa中清除WebView缓存?

时间:2012-08-22 11:27:48

标签: macos cocoa webview

如何在Cocoa应用程序中清除/刷新WebView缓存?

特别是,我想清除本地样式表的缓存。

我试过以下无济于事:

// Tried this before loadRequest
[[NSURLCache sharedURLCache] removeAllCachedResponses];

// Also tried this before and after loadRequest
[webView.mainFrame reloadFromOrigin];

即使用新版本替换WebView,仍然使用缓存的样式表。

2 个答案:

答案 0 :(得分:10)

其他建议的解决方案不适用于本地样式表(尽管它们应该适用于远程资源)。

我终于设法通过resourceLoadDelegate通过显式设置缓存策略来解决这个问题:

- (NSURLRequest *)webView:(WebView *)sender resource:(id)identifier willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)redirectResponse fromDataSource:(WebDataSource *)dataSource {
    request = [NSURLRequest requestWithURL:[request URL] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:[request timeoutInterval]];
    return request;
}

有趣的东西。

答案 1 :(得分:0)

查看NSURLCache Class Reference.

- (id)initWithMemoryCapacity:(NSUInteger)memoryCapacity diskCapacity:(NSUInteger)diskCapacity diskPath:(NSString *)path 
//set memoryCapacity and diskCapacity to 0 bytes and diskPath to nil

NSURLCache *Cache = [[NSURLCache alloc] initWithMemoryCapacity:0 diskCapacity:0 diskPath:nil];
[NSURLCache setSharedURLCache:Cache];