[英]How to clear UIWebView cache in iOS 7.1 in iPad?
我需要显示一个UIWebView,它可以打开本地html,并从远程服务器获取。 每次,由于iOS缓存系统,UIWebView都会显示不正确的数据。
我做了很多尝试来解决这个问题,但是没有用:
1)当UIViewController开始加载时,以编程方式添加UIWebView。 UIViewController消失后,停止加载UIWebView,然后释放UIWebView。
2)忽略本地缓存数据:
NSURL *websiteUrl = [NSURL fileURLWithPath:localHtmlPath]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:websiteUrl]; [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData]; [self.webView loadRequest:request];
3)当UIViewController消失时清除缓存
[[NSURLCache sharedURLCache] removeAllCachedResponses]; for(NSHTTPCookie *cookie in [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies]) { if([[cookie domain] isEqualToString:localHtmlPath]) { [[NSHTTPCookieStorage sharedHTTPCookieStorage] deleteCookie:cookie]; } }
4)禁用缓存
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { NSURLCache *sharedCache = [[NSURLCache alloc] initWithMemoryCapacity:0 diskCapacity:0 diskPath:nil]; [NSURLCache setSharedURLCache:sharedCache]; }
5)通过驯服NSURLCache降低iOS内存利用率
按照教程链接
- (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在缓存中存在错误。 此外,在加载本地html文件时,不使用NSURLCache。 UIWebView具有自己的缓存,我们无法控制它。 我的解决方案如下。
1)使用NSURLProtocol类的子类来拦截加载HTML文件。 可以修改响应头,以便插入无缓存头。 例如,对于方案file://
,
- (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文件后,让我们再次重新加载。 (执行UIWebView.reload()
)例如,可以在UIWebViewDelegate的webViewDidFinishLoad:
方法中完成此操作。 (为避免无限重装,请通过引入flag变量只检查一次。)然后,重装的html文件(和其他资源)是正确的。
就我而言,通过上述方法可以正确显示内容。
但是,我们尚无法清除UIWebView的缓存。 UIWebView的内存泄漏仍然存在。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.