Xamarin iOS clear cache from WKWebView

2019-06-03 20:14发布

问题:

I am doing following to clear the cache from the WkWebView. I would like to know how do I confirm that the cache is cleared

 var request = new NSUrlRequest (webURL, NSUrlRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData, 0);

 NSUrlCache.SharedCache.RemoveAllCachedResponses ();
 NSUrlCache.SharedCache.MemoryCapacity = 0;
 NSUrlCache.SharedCache.DiskCapacity = 0;

Is there a way to print the cache when making the request

回答1:

From this question looks like you do this (c# version) for iOS 9 and it will print out which records are deleted:

var websiteDataTypes = new NSSet<NSString>(new []
{
    //Choose which ones you want to remove
    WKWebsiteDataType.Cookies,
    WKWebsiteDataType.DiskCache,
    WKWebsiteDataType.IndexedDBDatabases,
    WKWebsiteDataType.LocalStorage,
    WKWebsiteDataType.MemoryCache,
    WKWebsiteDataType.OfflineWebApplicationCache,
    WKWebsiteDataType.SessionStorage,
    WKWebsiteDataType.WebSQLDatabases
});

WKWebsiteDataStore.DefaultDataStore.FetchDataRecordsOfTypes (websiteDataTypes, (NSArray records) =>
{
    for (nuint i = 0; i < records.Count; i++) {
        var record = records.GetItem<WKWebsiteDataRecord> (i);

        WKWebsiteDataStore.DefaultDataStore.RemoveDataOfTypes (record.DataTypes, 
            new[] {record}, () => {Console.Write($"deleted: {record.DisplayName}");});
    }
});

Or for iOS 8, from ShingoFukuyama/WKWebViewTips you could check the subdirectories Cookies, Caches, WebKit in the Library directory are removed.

iOS 8

After much trial and error, I've reached the following conclusion:

Use NSURLCache and NSHTTPCookie to delete cookies and caches in the same way as you used to do on UIWebView.

If you use WKProccessPool, re-initialize it.

Delete Cookies, Caches, WebKit subdirectories in the Library directory.

Delete all WKWebViews