remove cache in wkwebview objective c

2019-08-01 01:31发布

问题:

I need to remove cache in wkwebview.I am using below code but no success.

 [[NSURLCache sharedURLCache]removeCachedResponseForRequest:request];
    [[NSURLCache sharedURLCache] removeAllCachedResponses];
    [[NSURLCache sharedURLCache] setDiskCapacity:0];
    [[NSURLCache sharedURLCache] setMemoryCapacity:0];

回答1:

NSSet *dataTypes = [NSSet setWithArray:@[WKWebsiteDataTypeDiskCache,
                                         WKWebsiteDataTypeMemoryCache,
                                         ]];
[[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:dataTypes
                                           modifiedSince:[NSDate dateWithTimeIntervalSince1970:0]
                                       completionHandler:^{
        }];


回答2:

Try setting up the cache first when the application loads.

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

}

Once you have it properly configured, then when you need to purge the cache (for example in applicationDidReceiveMemoryWarning or when you close a UIWebView) just call:

[[NSURLCache sharedURLCache] removeAllCachedResponses];

Another thing to is you might want to try clearing the cookieStorage. I know this will reset sites you were logged into and such. Hope this helps.

NSHTTPCookie *cookie;
NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
for (cookie in [storage cookies])
{
    [storage deleteCookie:cookie];
}