5

I'm trying to write a controller with a webview and I need WKNavigationDelegate methods, the problem is that these methods are not being executed at all.

This is my controller:

import UIKit
import WebKit

public class WebViewController: UIViewController {

    private let webView: WKWebView = WKWebView()

    override public func viewDidLoad() {
        super.viewDidLoad()

        webView.navigationDelegate = self
        webView.isUserInteractionEnabled = true

        view = webView
    }
}

extension WebViewController: WKNavigationDelegate {
    private func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
        debugPrint("didCommit")
    }

    private func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        debugPrint("didFinish")
    }

    private func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
        debugPrint("didFail")
    }
}

This controller is being added to a top view controller using a container view, also the webview loads the website correctly. Has anyone had a similar problem or knows if I'm doing something wrong

3
  • Did you tried adding breakpoints in each method? Commented Apr 22, 2019 at 13:00
  • @Shabirjan yes I did, that's how I was testing it Commented Apr 22, 2019 at 13:01
  • Ok just a hint, try to remove private from each Delegate methods and try. Commented Apr 22, 2019 at 13:04

1 Answer 1

9

It looks like you are adding private with WKWebViewDelegate Methods, Remove those like this and it will work.

extension ViewController: WKNavigationDelegate {
 func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
    debugPrint("didCommit")
}

 func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
    debugPrint("didFinish")
}

 func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
    debugPrint("didFail")
}

} enter image description here Try this out, Also don't forgot to load URL in WebView or whatever you want to load.

Sign up to request clarification or add additional context in comments.

8 Comments

That doesn't work and I'm loading the url correctly
Well i created demo project and these Delegates methods are all being fired.
The public visibility was necessary, stupid mistake. Thanks
BTW explicit marking these delegates Public are not necessary.
Are you sure Shabir? Have you tried that? I've tested without the public modifier and it doesn't work, XCode also presents the following message: "Instance method 'webView(_:didCommit:)' nearly matches optional requirement..."
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.