2016-12-31 83 views
0

我想清除的UIWebView当应用终止时,URLCache,Javascript(本地存储)Swift在应用终止时清除webview缓存

我在一个按钮上按下了以下代码。该功能在按钮按下时按预期工作。

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

} 

每当我终止应用程序,我得到以下错误:

enter image description here

enter image description here

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

谢谢!

+0

为什么不尝试在didFinishLaunchingWithOptions中清除它? – iYoung

+0

在那里得到完全相同的错误。 –

回答

0

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

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

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

看起来像视图控制器不具有的WebView的实例

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

的WebView的

清楚一切都在viewWillDisappear

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

问题的WebView实例不存在,当你即将关闭该应用程序,那么当你启动一个应用程序并在特定的视图中使用该实例显示时,你在App Delegate内部实例化一个webview。这种方式webview实例应该每次都可用,在关闭应用程序之前调用clearEverything。

+0

仍然存在JavaScript高速缓存,尚未清除 –