gpt4 book ai didi

javascript - Swift 在应用程序终止时清除 webview 缓存

转载 作者:行者123 更新时间:2023-11-28 05:10:44 25 4
gpt4 key购买 nike

我想在应用终止时清除 UIWebViewURLCache、Javascript(本地存储)

我在按下按钮时实现了以下代码。该功能在按下按钮时按预期工作。

func clearEverything() {
print("cleared")
URLCache.shared.removeAllCachedResponses()
URLCache.shared.diskCapacity = 0
URLCache.shared.memoryCapacity = 0

webView.stringByEvaluatingJavaScript(from: "localStorage.clear();")
let cookieJar = HTTPCookieStorage.shared
for cookie in cookieJar.cookies! {
cookieJar.deleteCookie(cookie)
}
UserDefaults.standard.synchronize()

}

AppDelegate的函数applicationWillTerminate中,我使用了以下代码:

func applicationWillTerminate(_ application: UIApplication) {
print("app terminated")
clearEverything()
}

func clearEverything() {
print("cleared from App Delegate")
URLCache.shared.removeAllCachedResponses()
URLCache.shared.diskCapacity = 0
URLCache.shared.memoryCapacity = 0

ViewController().webView.stringByEvaluatingJavaScript(from: "localStorage.clear();")
let cookieJar = HTTPCookieStorage.shared
for cookie in cookieJar.cookies! {
cookieJar.deleteCookie(cookie)
}
UserDefaults.standard.synchronize()

}

每当我终止应用程序时,都会收到以下错误:

enter image description here

enter image description here

建议我在不导致应用程序崩溃的情况下实现此功能的最佳方法。

谢谢!!

最佳答案

看起来 ViewController 没有 webview 的实例

ViewController().webView.stringByEvaluatingJavaScript(from: "localStorage.clear();")

清除webview的viewWillDisappear中的所有内容

override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
// codes
}

问题是当您要关闭应用程序时,webview 实例不存在,那么当您启动应用程序时,如何在 App Delegate 中实例化一个 webview,并使用该实例在特定 View 中显示。这样,每次在关闭应用程序之前调用clearEverything 时,webview 实例都应该可用。

关于javascript - Swift 在应用程序终止时清除 webview 缓存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41406438/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com