任何人都使用WKWebview
并尝试清除缓存?如果有,该怎么办?任何一个例子?
P.S。 :正常的NSURLCache无效。
答案 0 :(得分:2)
您无法仅使用NSURLCache删除缓存。 经过多次尝试,我可以通过以下步骤清除缓存(从iOS 8.1.1开始):
Caches
中的Library
目录。下次创建WKWebView时,应清除缓存。
答案 1 :(得分:2)
我能够通过让我的WKWebView评估window.location.reload来解决这个问题。我在网络视图上有一个点击手势识别器,每当它检测到双击时有2次触摸,我运行以下内容:
webView.evaluateJavaScript("window.location.reload(true)", completionHandler: nil);
希望这有帮助。
答案 2 :(得分:1)
iOS 9.0及更高版本的类似内容:
let store: WKWebsiteDataStore = WKWebsiteDataStore.default()
let dataTypes: Set<String> = WKWebsiteDataStore.allWebsiteDataTypes()
store.fetchDataRecords(ofTypes: dataTypes, completionHandler: { (records: [WKWebsiteDataRecord]) in
store.removeData(ofTypes: dataTypes, for: records, completionHandler: {
// do your thing here
})
})
答案 3 :(得分:1)
Swift 3.x版本的@ Esqarrouth的帖子
func clearCache() {
if #available(iOS 9.0, *) {
let websiteDataTypes = NSSet(array: [WKWebsiteDataTypeDiskCache, WKWebsiteDataTypeMemoryCache])
let date = NSDate(timeIntervalSince1970: 0)
WKWebsiteDataStore.default().removeData(ofTypes: websiteDataTypes as! Set<String>, modifiedSince: date as Date, completionHandler:{ })
} else {
var libraryPath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.libraryDirectory, FileManager.SearchPathDomainMask.userDomainMask, false).first!
libraryPath += "/Cookies"
do {
try FileManager.default.removeItem(atPath: libraryPath)
} catch {
print("error")
}
URLCache.shared.removeAllCachedResponses()
}
}
答案 4 :(得分:1)
曾为
Swift 3.版本。
旧版本Swift
import Foundation
import WebKit
func removeWebData() {
if #available(iOS 9.0, *) {
let websiteDataTypes = WKWebsiteDataStore.allWebsiteDataTypes()
let date = NSDate(timeIntervalSince1970: 0)
WKWebsiteDataStore.default().removeData(ofTypes: websiteDataTypes, modifiedSince: date as Date, completionHandler: {
#if DEBUG
print("remove all data in iOS9 later")
#endif
})
}else {
// Remove the basic cache.
URLCache.shared.removeAllCachedResponses()
// Delete system cookie store in the app
let storage = HTTPCookieStorage.shared
if let cookies = storage.cookies {
for cookie in cookies {
storage.deleteCookie(cookie)
}
}
do {
// folder 를 삭제하는 대신 contents 를 삭제하는 이유?
// MainVC 가 호출되면 cache, cookie가 발생하므로 로딩시 확인된 cache, cookie 폴더의
// contents 에 대해서만 삭제 진행.
// Clear web cache
try deleteLibraryFolderContents(folder: "Caches")
// Remove all cookies stored by the site. This includes localStorage, sessionStorage, and WebSQL/IndexedDB.
try deleteLibraryFolderContents(folder: "Cookies")
// Removes all app cache storage.
try deleteLibraryFolder(folder: "WebKit")
} catch {
#if DEBUG
print("Delete library folders error in iOS9 below")
#endif
}
}
}
/**
Delete folder in library
- parameter folder: a folder you want to delete
- throws: throws an error
*/
func deleteLibraryFolder(folder: String) throws {
let manager = FileManager.default
let library = manager.urls(for: .libraryDirectory, in: .userDomainMask).first!
let dir = library.appendingPathComponent(folder)
try manager.removeItem(at: dir)
}
/**
Delete contents in library folder
- parameter folder: target folder
- throws: throws an error
*/
private func deleteLibraryFolderContents(folder: String) throws {
let manager = FileManager.default
let library = manager.urls(for: FileManager.SearchPathDirectory.libraryDirectory, in: .userDomainMask)[0]
let dir = library.appendingPathComponent(folder)
let contents = try manager.contentsOfDirectory(atPath: dir.path)
for content in contents {
do {
try manager.removeItem(at: dir.appendingPathComponent(content))
} catch where ((error as NSError).userInfo[NSUnderlyingErrorKey] as? NSError)?.code == Int(EPERM) {
// "EPERM: operation is not permitted". We ignore this.
#if DEBUG
print("Couldn't delete some library contents.")
#endif
}
}
}
答案 5 :(得分:0)
它对我有用
if #available(iOS 9.0, *) {
let websiteDataTypes = NSSet(array: [WKWebsiteDataTypeDiskCache, WKWebsiteDataTypeMemoryCache])
let date = NSDate(timeIntervalSince1970: 0)
WKWebsiteDataStore.defaultDataStore().removeDataOfTypes(websiteDataTypes as! Set<String>, modifiedSince: date, completionHandler:{ })
}
else
{
NSURLCache.sharedURLCache().removeAllCachedResponses()
}
答案 6 :(得分:0)
我需要几个小时,但这对我有用! 在loadRequest之后,我做了一个reloadFromOrigin!所以我强制空缓存! [WKWebView loadRequest:request]; [WKWebView reloadFromOrigin];
答案 7 :(得分:0)
# WKWebView+Clean.swift
import WebKit
extension WKWebView {
class func clean() {
guard #available(iOS 9.0, *) else {return}
HTTPCookieStorage.shared.removeCookies(since: Date.distantPast)
WKWebsiteDataStore.default().fetchDataRecords(ofTypes: WKWebsiteDataStore.allWebsiteDataTypes()) { records in
records.forEach { record in
WKWebsiteDataStore.default().removeData(ofTypes: record.dataTypes, for: [record], completionHandler: {})
#if DEBUG
print("WKWebsiteDataStore record deleted:", record)
#endif
}
}
}
}
示例:
import WebKit
...
WKWebview.clean()
答案 8 :(得分:0)
获取缓存字典路径并将其删除
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSError *error;
BOOL success = [fileManager removeItemAtPath:documentsPath error:&error];
NSLog(@"%d",success);
答案 9 :(得分:0)
private func deleteCache(){
if #available(iOS 9.0, *) {
let websiteDataTypes = NSSet(array: [WKWebsiteDataTypeDiskCache, WKWebsiteDataTypeMemoryCache])
let date = NSDate(timeIntervalSince1970: 0)
WKWebsiteDataStore.default().removeData(ofTypes: websiteDataTypes as! Set<String>, modifiedSince: date as Date, completionHandler:{ })
} else {
var libraryPath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.libraryDirectory, FileManager.SearchPathDomainMask.userDomainMask, false).first!
libraryPath += "/Cookies"
do {
try FileManager.default.removeItem(atPath: libraryPath)
} catch {
print("error")
}
URLCache.shared.removeAllCachedResponses()
}
}
答案 10 :(得分:0)
swift5
URLCache.shared.removeAllCachedResponses()