【问题标题】:Swift Clear webview cache on app terminationSwift 在应用程序终止时清除 webview 缓存
【发布时间】:2016-12-31 07:37:57
【问题描述】:

我想在应用终止时清除 UIWebViewURLCache, Javascript(local storage)

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

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的func 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()

}

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

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

谢谢!!

【问题讨论】:

  • 你为什么不尝试在 didFinishLaunchingWithOptions 中清除它?
  • 那里得到完全相同的错误。

标签: javascript ios uiwebview swift3


【解决方案1】:

好像 ViewController 没有 webview 的实例

ViewController().webView.stringByEvaluatingJavaScript(来自: "localStorage.clear();")

清除webview的viewWillDisappear中的所有内容

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

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

【讨论】:

  • 仍然存在 JavaScript 缓存,没有被清除
【解决方案2】:

我得到了这个工作,但只有当应用程序被 VC 终止并显示 UIWebView 时。

override func viewDidLoad() { 
NotificationCenter.default.addObserver(self, selector: #selector(applicationWillTerminate), name: NSNotification.Name.UIApplicationWillTerminate, object: nil)
}

func applicationWillTerminate() {
    clearBtnPressed(Any.self)
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-12
    • 2012-06-14
    • 1970-01-01
    • 2018-12-12
    相关资源
    最近更新 更多