26

I need UIWebView to display some local .webarchive file. But images there have same names, so UIWebView shows only one image all the time. How can I clear the cache?

Thanks in advance

Mike Rychev
  • 261
  • 1
  • 3
  • 4

9 Answers9

32
// Flush all cached data
[[NSURLCache sharedURLCache] removeAllCachedResponses];
Caleb Shay
  • 2,531
  • 1
  • 17
  • 13
  • 1
    This doesn't work for me, but YMMV (specifically for stylesheets included with a `link` tag). I'm using the `-loadHTMLString:baseURL:` method on `UIWebView`. Installing an NSURLCache subclass did the trick, but I wouldn't use it outside a debugging scenario. – Frank Schmitt Nov 15 '12 at 19:20
  • I was stuck with my UIWebView having cached a 301 redirect. Clearing Safari's cache didn't help, but putting this call in my AppDelegate's didFinishLaunchingWithOptions (just as a one-time thing) finally got the cached redirect removed. – Ghazgkull May 27 '15 at 18:09
17
NSURLRequest* request = [NSURLRequest requestWithURL:fileURL cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60.0];

[webView loadRequest:request];

(now with typo fixed)

feesta
  • 29
  • 1
  • 7
Biranchi
  • 15,173
  • 20
  • 115
  • 154
  • 7
    I'm having the same problem here, so I tried this out, and unfortunately this doesn't work. I suspect that it's only the actual html file itself that gets loaded ignoring the cache. We need some way of making files loaded by the page itself to ignore the cache... – Ben Clayton Aug 02 '10 at 13:42
11

I've had this issue myself with script and css files being cached.

My solution was to put a cache-busting parameter on the src url:

<script src='myurl?t=1234'> ...

where t=1234 changes each time the page is loaded.

TomSwift
  • 38,979
  • 11
  • 115
  • 147
  • 1
    wow man!! ooosssummm !! in my case i used it like this : – Deepukjayan Aug 01 '13 at 05:23
  • 1
    This is great and very easy to implement. An important detail: you dont need to actually modify the name of the file on disk, you just add the query param to the script tag (or whatever you're working with) and the cache references the updated file on disk (that has the same filename it always did). Great solution. – Alfie Hanssen Sep 10 '13 at 14:30
  • Works on Android too ! – Jatin Aug 06 '15 at 05:30
10

Using

[[NSURLCache sharedURLCache] removeAllCachedResponses];

BEFORE make the call or when you load the view controller, this is an static function that remove all cache data for responses. Only using cachePolicy it was not enought, i see that uiwebview could refresh the html document but not the linked document like CSS, JS or images.

I try this solution and it works.

 if (lastReq){
    [[NSURLCache sharedURLCache] removeCachedResponseForRequest:lastReq];
    [[NSURLCache sharedURLCache] removeAllCachedResponses];

}

lastReq=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:localUrl]
                                   cachePolicy:NSURLRequestReloadIgnoringCacheData
                               timeoutInterval:10000];
[lastReq setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];

[self.mainWebView loadRequest:lastReq];

--First of all, i remove the cache for the last request and call to remove all other cache ( i think this is not so important) --Then i create a nsurlrequest and ignoringLocalCacheData --finally, load the new request

I check it and it reload all files (html, css, js and images).

jgorozco
  • 583
  • 10
  • 11
  • Should mention where you do this. – Niklas Berglund Oct 01 '13 at 18:19
  • Also you're setting cachePolicy twice. On purpose? – Niklas Berglund Oct 13 '13 at 16:37
  • Second one would not been necessary, but i dont know why it works better, if you dont put it, sometimes keep having the cache data. I test this without the setCachePolicy but only works sometimes. I put it and works most of the times. I keep searching a 100% solution for this problem, but right now this is my best approach :-) – jgorozco Oct 14 '13 at 07:20
6
//to prevent internal caching of webpages in application
NSURLCache *sharedCache = [[NSURLCache alloc] initWithMemoryCapacity:0 diskCapacity:0 diskPath:nil];
[NSURLCache setSharedURLCache:sharedCache];
[sharedCache release];
sharedCache = nil;

try using this. It will clear the url cache memory of your application.

Naveen Shan
  • 9,082
  • 3
  • 26
  • 43
  • 1
    This is an great "sledgehammer" approach for local assets, but it could be problematic in an app that also does remote loading of assets, since the shared URL cache is an app-wide setting. – Frank Schmitt Nov 15 '12 at 19:25
  • Agree, this is not the best way to do this. It'll kill your cache but leave you with a cache with no capacity. if you're looking for a simple reset/startOver it's `[[NSURLCache sharedURLCache] removeAllCachedResponses];` – Alfie Hanssen Mar 28 '13 at 21:52
  • 2
    This is the only approach that worked for me - for some reason `removeAllCachedResponses` did nothing. – Nestor Sep 24 '13 at 09:30
4

I'm working with some designers editing the CSS files used by some web views in an app. They were complaining that changes to the stylesheets weren't being reflected in the app, and a bit of debugging with Charles confirmed that they weren't being reloaded. I tried seemingly every answer on StackOverflow, to no avail.

What finally did the trick was creating an NSURLCache subclass that overrides -cachedResponseForRequest:

- (NSCachedURLResponse*)cachedResponseForRequest:(NSURLRequest*)request
{
    if ([[[[request URL] absoluteString] pathExtension] caseInsensitiveCompare:@"css"] == NSOrderedSame)
        return nil;
    else
        return [super cachedResponseForRequest:request];
}

I then install it with a reasonable memory and disk capacity:

NSURLCache *currentCache = [NSURLCache sharedURLCache];
NSString *cachePath = [cachesDirectory() stringByAppendingPathComponent:@"DebugCache"];

DebugURLCache *cache = [[DebugURLCache alloc] initWithMemoryCapacity:currentCache.memoryCapacity diskCapacity:currentCache.diskCapacity diskPath:cachePath];
[NSURLCache setSharedURLCache:cache];
[cache release];

(cachesDirectory() is a function that returns /Library/Caches under the application directory on iOS).

As you can tell by the name, I'm using this only in the debug configuration (using the Additional Preprocessor Flags build setting and some #ifdefs).

Dan Abramov
  • 241,321
  • 75
  • 389
  • 492
Frank Schmitt
  • 24,850
  • 8
  • 56
  • 69
  • i get error no visible @interface for UIViewController declares selector cachedResponseForRequest – Jim True Sep 02 '13 at 15:42
  • @Frank Schmitt I'm loading a web view which has images. I have tried your solution but could not get the images to reload. I checked if the images are cached on the file system and I could not find them in file system. I'm assuming they are cached in the memory itself and will only be freed on demand for more memory. I tried to force memory limit to 0 by [[NSURLCache sharedURLCache] setMemoryCapacity:0]; [[NSURLCache sharedURLCache] setDiskCapacity:0]; but still could not get the images to reload. Any suggestion would help. Thanks. – Ravi Nov 15 '13 at 15:37
1

For swift 3

//to remove cache from UIWebview
URLCache.shared.removeAllCachedResponses()
    if let cookies = HTTPCookieStorage.shared.cookies {
        for cookie in cookies {
            HTTPCookieStorage.shared.deleteCookie(cookie)
        }
    }
Hardik Thakkar
  • 13,424
  • 2
  • 80
  • 72
  • I used this method in my application but when user search some thing in the google after launching application again when user tap search textfield on the google the user can see what he searched before – Saeed Rahmatolahi Sep 23 '17 at 12:45
0

Use following code:

NSString *cacheDir=[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];  
  [[NSFileManager defaultManager]removeItemAtPath:cacheDir error:nil];
Akshay Aher
  • 2,495
  • 2
  • 16
  • 33
Kumaresan P
  • 119
  • 1
  • 8
  • This seems unrelated to the question asked, and also seems pretty dangerous. The Cache directory has far more use than standard http or webview caching so deleting the entire directory is not a solution that most people would use. – Alfie Hanssen Mar 28 '13 at 13:50
  • It's good to know how to access and remove the entire Cache Directory. Documentation reports that iOS ["may delete the Caches/ directory to free up disk space"](https://developer.apple.com/library/ios/documentation/FileManagement/Conceptual/FileSystemProgrammingGuide/FileSystemOverview/FileSystemOverview.html#//apple_ref/doc/uid/TP40010672-CH2-SW28). Though deleting the /Cache directory isn't best practice, it's an option that's on the table for devs who may need to clear the On-Disk cache, a function that cannot be done using [NSURLCache removeAllCachedResponses] which only clears Memory. – JThora Dec 12 '14 at 19:25
  • Further, the Cache Directory should be replaced after removing the original: [[NSFileManager defaultManager]createDirectoryAtPath:cacheDir withIntermediateDirectories:NO attributes:nil error:nil]; – JThora Dec 12 '14 at 19:48
0

this work like a charm !

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

//Clear All Cookies
for(NSHTTPCookie *cookie in [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies]) {
    [[NSHTTPCookieStorage sharedHTTPCookieStorage] deleteCookie:cookie];
}