1

I'm currently writing a web view application using WKWebView, which should show a custom error page when there is no internet connection while loading a page. I've tried to handle this by calling a method of WKNavigationDelegate, but it's never called. I'm new to Swift and I already tried some solutions I've found here on stackoverflow, but none of them worked for me. Am I doing something wrong?

import UIKit
import WebKit

class ViewController: UIViewController, WKUIDelegate, WKNavigationDelegate {

    var webView: WKWebView!
    
    override func loadView() {
        let webConfiguration = WKWebViewConfiguration()
        webView = WKWebView(frame: .zero, configuration: webConfiguration)
        webView.uiDelegate = self
        webView.navigationDelegate = self
        view = webView
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        let myURL = URL(string:"https://google.com")
        let myRequest = URLRequest(url: myURL!)
        webView.load(myRequest)
    }

    func webView(webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: NSError)
    {
        let url = Bundle.main.url(forResource: "no_connection", withExtension: "html")!
        webView.loadFileURL(url, allowingReadAccessTo: url)
        let request = URLRequest(url: url)
        webView.load(request)
    }
}
david
  • 13
  • 4
  • 2
    If the sole issue is you being unable to check reachability, may I recommend you use something like solutions proposed here: https://stackoverflow.com/questions/30743408/check-for-internet-connection-with-swift Also, did you try to log something inside the function to see if it is actually not being called and there is no problem with your resource? – Orion Cygnus Sep 08 '21 at 13:13

1 Answers1

1

The signature func(webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: NSError) { } is incorrect.
Try instead func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) { }.
There should be even a warning, telling you that with the first signature you aren't using a delegate function:
enter image description here

finebel
  • 2,227
  • 1
  • 9
  • 20