How to clear UIWebView cache in iOS 7.1 in iPad?
我需要显示一个从远程服务器获取本地HTML的uiWebView。每次,uiWebView都会显示不正确的数据,因为iOS缓存系统。
我做了很多尝试来解决这个问题,但都不起作用:
1)当uiviewController开始加载时,以编程方式添加uiwebview。uiviewController消失后,停止加载uiWebView,并释放uiWebView。
2)忽略本地缓存数据:
1 2 3 4 | NSURL *websiteUrl = [NSURL fileURLWithPath:localHtmlPath]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:websiteUrl]; [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData]; [self.webView loadRequest:request]; |
3)当uiviewcontroller消失时清除缓存
1 2 3 4 5 6 7 8 | [[NSURLCache sharedURLCache] removeAllCachedResponses]; for(NSHTTPCookie *cookie in [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies]) { if([[cookie domain] isEqualToString:localHtmlPath]) { [[NSHTTPCookieStorage sharedHTTPCookieStorage] deleteCookie:cookie]; } } |
4)禁用缓存
1 2 3 4 5 | - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { NSURLCache *sharedCache = [[NSURLCache alloc] initWithMemoryCapacity:0 diskCapacity:0 diskPath:nil]; [NSURLCache setSharedURLCache:sharedCache]; } |
5)通过控制nsurlcache降低iOS内存利用率
遵循教程链接
1 2 3 4 5 6 7 8 9 10 11 12 | - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { int cacheSizeMemory = 4*1024*1024; // 4MB int cacheSizeDisk = 32*1024*1024; // 32MB NSURLCache *sharedCache = [[NSURLCache alloc] initWithMemoryCapacity:cacheSizeMemory diskCapacity:cacheSizeDisk diskPath:@"nsurlcache"]; [NSURLCache setSharedURLCache:sharedCache]; } - (void)applicationDidReceiveMemoryWarning:(UIApplication *)application { [[NSURLCache sharedURLCache] removeAllCachedResponses]; } |
6)遵循这个链接来防止CSS缓存。
上述方法都不起作用。有什么办法吗?
据我所知,最新的sdk ios8.0在缓存中有一个bug。此外,加载本地HTML文件时,不使用nsurlcache。uiWebView有自己的缓存,我们无法控制。我的解决方案如下。
1)使用nsurlprotocol类的子类拦截加载HTML文件。可以修改响应头以便不插入缓存头。例如,对于方案
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | - (void)startLoading { NSData *data = [NSData dataWithContentsOfFile:self.request.URL.path]; NSDictionary *headers = [NSDictionary dictionaryWithObjectsAndKeys: [self.request.allHTTPHeaderFields objectForKey:@"Accept"], @"Accept", @"no-cache", @"Cache-Control", @"no-cache", @"Pragma", [NSString stringWithFormat:@"%d", (int)[data length]], @"Content-Length", nil]; NSHTTPURLResponse *response = [[NSHTTPURLResponse alloc] initWithURL:request.URL statusCode:200 HTTPVersion:@"1.1" headerFields:headers]; [self.client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageAllowedInMemoryOnly]; [self.client URLProtocol:self didLoadData:data]; [self.client URLProtocolDidFinishLoading:self]; |
2)在加载了由于uiwebview缓存而不正确的html文件之后,让我们再次重新加载。(do
在我的例子中,通过上述方法可以正确地显示内容。
但是,我们还不能清除uiwebview的缓存。uiWebView的内存泄漏仍然存在。