Search code examples
iosswifterror-handlinguiwebview

switch view if the Webview can't loading the URL?


I have 2 views on my screen first is the Webview and the second is a static view "errorView" with the error message "set to hidden". I am trying to load the errorView if we have an error loading website to Webview.

@objc private func loadURL() {
 
        guard let url = URL(string: "https://www.hackingwi") else {
            self.errroLoadingWebView.isHidden = false
            return
        }
        webView?.load(URLRequest(url: url))
        webView?.allowsBackForwardNavigationGestures = true
    }

Solution

  • You can use WKNavigationDelegate.

    set delegate

    webView.uiDelegate = self
    webView.navigationDelegate = self
    
    class StaticWebPageVC: WKNavigationDelegate, WKUIDelegate {
        func webView(_: WKWebView, didFinish _: WKNavigation!) {
            // Web view loaded
        }
        
        func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
            // Show error view
        }
        
        func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
            // Show error view
        }
    }