Search code examples
iosswiftwkwebviewuivewcontroller

How can I clear WKWebView when trying to add a new webView from unwind segue?


I have an app that uses at WKWebView to display local file paths. It segues to another view controller, then unwinds to the original controller, with a new html file path. I have got it loading the new file path but only after the index file flashes for a second. Anyway to clear this view?

override func viewWillAppear(_ animated: Bool) {

if unwindingFromPost == true {

      let htmlPath = Bundle.main.path(forResource: "card/card", ofType: "html", inDirectory: "pickles_ui")

      let url = URL(fileURLWithPath: htmlPath!)
      let request = URLRequest(url: url)

      webView.scrollView.bounces = false

      webView.load(request)

    } else {
        let htmlPath = Bundle.main.path(forResource: "index", ofType: "html", inDirectory: "pickles_ui")

        let url = URL(fileURLWithPath: htmlPath!)
        let request = URLRequest(url: url)

        webView.scrollView.bounces = false

        webView.load(request)
  }
}

}


Solution

  • You might have this behaviour because it might show the previous url in webview just like a second before loading the new one. I can suggest a workaround like, loading a blank view on your webView when view disappears (viewWillDisAppear method):

    In your main viewController try adding following:

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        let url = URL(string: "about:blank")
        let request = URLRequest(url: url!)
        myGraphView.loadRequest(request)
    }