WKWebView如何清除緩存

WKWebView如何清除緩存

iOS7.0只有UIWebView, 而iOS8.0是有WKWebView, 但8.0的WKWebView沒有刪除緩存方法。iOS9.0之后就開始支持啦。
所以使用時(shí)候一定要適配iOS9.0以上

適用場(chǎng)景

清除WKWebView的緩存,讓H5頁(yè)面一刷新就更新至最新的頁(yè)面

選擇在合適邏輯加上以下代碼:

清除所有的緩存

- (void)deleteWebCache {
//allWebsiteDataTypes清除所有緩存
 NSSet *websiteDataTypes = [WKWebsiteDataStore allWebsiteDataTypes];

    NSDate *dateFrom = [NSDate dateWithTimeIntervalSince1970:0];

    [[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:websiteDataTypes modifiedSince:dateFrom completionHandler:^{
        
    }];
}

自定義清除緩存

- (void)deleteWebCache {
/*
     在磁盤緩存上。
     WKWebsiteDataTypeDiskCache,
     
     html離線Web應(yīng)用程序緩存。
     WKWebsiteDataTypeOfflineWebApplicationCache,
     
     內(nèi)存緩存。
     WKWebsiteDataTypeMemoryCache,
     
     本地存儲(chǔ)。
     WKWebsiteDataTypeLocalStorage,
     
     Cookies
     WKWebsiteDataTypeCookies,
     
     會(huì)話存儲(chǔ)
     WKWebsiteDataTypeSessionStorage,
     
     IndexedDB數(shù)據(jù)庫(kù)。
     WKWebsiteDataTypeIndexedDBDatabases,
     
     查詢數(shù)據(jù)庫(kù)。
     WKWebsiteDataTypeWebSQLDatabases
     */
    NSArray * types=@[WKWebsiteDataTypeCookies,WKWebsiteDataTypeLocalStorage];
    
    NSSet *websiteDataTypes= [NSSet setWithArray:types];
    NSDate *dateFrom = [NSDate dateWithTimeIntervalSince1970:0];

    [[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:websiteDataTypes modifiedSince:dateFrom completionHandler:^{

    }];
}

但開發(fā)app必須要兼容所有iOS版本,可是iOS8,iOS7沒有這種直接的方法,那該怎么辦呢?
(iOS7.0只有UIWebView, 而iOS8.0是有WKWebView, 但8.0的WKWebView沒有刪除緩存方法。)
針對(duì)與iOS7.0、iOS8.0、iOS9.0 WebView的緩存,我們找到了一個(gè)通吃的辦法:

NSString *libraryDir = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,   
NSUserDomainMask, YES)[0];
NSString *bundleId  =  [[[NSBundle mainBundle] infoDictionary]   
objectForKey:@"CFBundleIdentifier"];
NSString *webkitFolderInLib = [NSString stringWithFormat:@"%@/WebKit",libraryDir];
NSString *webKitFolderInCaches = [NSString   
stringWithFormat:@"%@/Caches/%@/WebKit",libraryDir,bundleId];
 NSString *webKitFolderInCachesfs = [NSString   
 stringWithFormat:@"%@/Caches/%@/fsCachedData",libraryDir,bundleId];

NSError *error;
/* iOS8.0 WebView Cache的存放路徑 */
[[NSFileManager defaultManager] removeItemAtPath:webKitFolderInCaches error:&error];
[[NSFileManager defaultManager] removeItemAtPath:webkitFolderInLib error:nil];

/* iOS7.0 WebView Cache的存放路徑 */
[[NSFileManager defaultManager] removeItemAtPath:webKitFolderInCachesfs error:&error];

如果文章幫到您,喜歡點(diǎn)個(gè)贊,謝謝您。

文章內(nèi)容出錯(cuò),記得留言,感激不盡。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容