Clear UIWebView cache when use local image file Clear UIWebView cache when use local image file objective-c objective-c

Clear UIWebView cache when use local image file


Other than renaming every file on each access, I've only seen one thing work for this and that is modifying the HTML with javascript to add a timestamp onto the image url so it tricks the webview into thinking it's a different file. Images (usually) load the same no matter what you put after the ? in their url. I think this would be easier than renaming every file each time you load the web view. Something like this (using jQuery):

<img src="myimg.jpg" /><script>$(function() {    $('img').each(function(i, el) {        $(el).attr('src', $(el).attr('src')+'?pizza='+(new Date()).getTime());    });});</script>

I guess this is assuming that this javascript loads and runs before the images are loaded, but in theory this should work.

For a little background, I've made a page in a webview that used RequireJS to asynchronously load quite a few files. I had the EXACT same problem that this question is talking about except that I was loading javascript files instead of images. The key to fixing this issue was adding a timestamp to every path of javascript file and thus tricking the webview (ex me.js?ts=236136236 and whatever.js?ts=3153524623). I found this to work great.

One other thing I needed to do was add a timestamp to the path of my HTML file when loading it into the webview like this:

[NSURL URLWithString:[[NSString stringWithFormat:@"%@/index.html?pizza=%f", webDirectoryPath, [[NSDate date] timeIntervalSince1970]]

I now can modify all the local files and each time the webview appears the changes come through.


You can try this, in your AppDelegate.m

+(void)initialize {  [[NSURLCache sharedURLCache] setDiskCapacity:0];  [[NSURLCache sharedURLCache] setMemoryCapacity:0];}


If your html didn't change and the only change was in image you should use UIWebView's reload message instead of loading request again.

Something like this:

- (void)reloadWebView:(id)sender{    if (self.loaded) {        [self.webView reload];    } else {        NSString *html = [[NSBundle mainBundle] pathForResource:@"web" ofType:@"html"];        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL fileURLWithPath:html]];        [self.webView loadRequest:request];        self.loaded = YES;    }}

You don't even need any manipulations with cache.