hpique
hpique

Reputation: 120324

How do you clear the WebView cache in Cocoa?

How do you clear/flush the WebView cache in a Cocoa app?

In particular, I would like to clear the cache of a local stylesheet.

I have tried the following to no avail:

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

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

Even replacing the WebView with a new one still uses the cached stylesheet.

Upvotes: 9

Views: 5560

Answers (2)

hpique
hpique

Reputation: 120324

The other suggested solutions didn't work for the local stylesheet (though they should work for remote resources).

I finally managed to solve this via the resourceLoadDelegate, by explicitly setting the cache policy:

- (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;
}

Fun stuff.

Upvotes: 10

Parag Bafna
Parag Bafna

Reputation: 22930

Take a look at 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];

Upvotes: 0

Related Questions