清除UIWebview缓存

Cha*_* SP 66 cocoa-touch uiwebview uikit ios

我使用UIWebview使用loadRequest:方法加载网页,当我离开那个场景时,我调用[self.webView stopLoading];并释放webView.

在第一次启动的活动监视器中,我已经看到实际内存增加了4MB,并且在多次启动/加载时,实际内存不会增加.它只增加一次.

我检查了webview的保留计数.这是正确的,即0.我认为UIWebView正在缓存一些数据.如何避免缓存或删除缓存数据?或者还有其他原因吗?

gro*_*msy 125

我实际上认为它可能会在您关闭时保留缓存的信息UIWebView.我试过UIWebView从我UIViewController那里删除一个,释放它,然后创建一个新的.当我回到一个地址而不必重新加载所有东西时(记得我以前UIWebView登录过的),新的记忆确切地记得我在哪里.

所以有几点建议:

[[NSURLCache sharedURLCache] removeCachedResponseForRequest:NSURLRequest];
Run Code Online (Sandbox Code Playgroud)

这将删除特定请求的缓存响应.还有一个调用将删除对以下所有请求运行的所有缓存响应UIWebView:

[[NSURLCache sharedURLCache] removeAllCachedResponses];
Run Code Online (Sandbox Code Playgroud)

之后,您可以尝试删除任何相关的cookie UIWebView:

for(NSHTTPCookie *cookie in [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies]) {

    if([[cookie domain] isEqualToString:someNSStringUrlDomain]) {

        [[NSHTTPCookieStorage sharedHTTPCookieStorage] deleteCookie:cookie];
    }
}
Run Code Online (Sandbox Code Playgroud)

斯威夫特3:

// Remove all cache 
URLCache.shared.removeAllCachedResponses()

// Delete any associated cookies     
if let cookies = HTTPCookieStorage.shared.cookies {
    for cookie in cookies {
        HTTPCookieStorage.shared.deleteCookie(cookie)
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 嗨,我试过[[NSURLCache sharedURLCache] removeAllCachedResponses] ;,但它不起作用,我仍然在缓存中有相同的图像...还有另一种解决方法吗? (9认同)
  • 是的,在这里,我正在获得持久登录,我认为UIWebView可能持有令牌太长时间.有什么想法吗? (3认同)

Tod*_*ddH 45

不要完全禁用缓存,这会损害您的应用程序性能,这是不必要的.重要的是在app启动时显式配置缓存并在必要时清除缓存.

因此,在application:DidFinishLaunchingWithOptions:配置缓存限制如下:

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

    // ... other launching code
}
Run Code Online (Sandbox Code Playgroud)

正确配置后,当需要清除缓存时(例如,applicationDidReceiveMemoryWarning在关闭a时或关闭时UIWebView),只需执行以下操作:

[[NSURLCache sharedURLCache] removeAllCachedResponses];
Run Code Online (Sandbox Code Playgroud)

你会看到内存已经恢复.我在这里写了关于这个问题的博客:http://twobitlabs.com/2012/01/ios-ipad-iphone-nsurlcache-uiwebview-memory-utilization/


Ins*_*ame 9

您可以通过执行以下操作禁用缓存:

NSURLCache *sharedCache = [[NSURLCache alloc] initWithMemoryCapacity:0 diskCapacity:0 diskPath:nil];
[NSURLCache setSharedURLCache:sharedCache];
[sharedCache release];
Run Code Online (Sandbox Code Playgroud)


Cod*_*ide 6

斯威夫特3.

// Remove all cache 
URLCache.shared.removeAllCachedResponses()

// Delete any associated cookies     
if let cookies = HTTPCookieStorage.shared.cookies {
    for cookie in cookies {
        HTTPCookieStorage.shared.deleteCookie(cookie)
    }
}
Run Code Online (Sandbox Code Playgroud)