2016-12-31 111 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高速緩存,尚未清除 –