Smorka
Smorka

Reputation: 1129

Inconsistent Behavior in WKNavigationDelegate

I am working on an app that mainly consist of a WKWebView. I monitor it's navigation status using the WKNavigationDelegate protocol.

I create my viewController as a WKNavigationDelegate

class ViewController: UIViewController, WKUIDelegate, WKNavigationDelegate, UIGestureRecognizerDelegate {
...
override func viewDidLoad() {
    ...
    webView.navigationDelegate = self
    ...

I load the request on the webview like so:

let gotoUrl = ... as? String
if let url = URL(string: gotoUrl) {
    let request = URLRequest(url: url)
    webView.load(request)            
}

And then the delegate methods:

    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        print("Successfully loaded")
    }

    func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
        print("Did commit navigation")
    }

    func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
        print("Start Provisional navigation")
    }

    func webViewWebContentProcessDidTerminate(_ webView:WKWebView) {
        print("request failed")
    }

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

    func webView(_ webView: WKWebView, didFailProvisionalNavigation: WKNavigation!, withError: Error) {
        print("request failed")
    }

This works fine for my webapps initial url: https://example.com/app/ Then the delegate methods are called.

When the app is opened from a notification I want to direct the webview to a specific part of the webapp. However when i load an url that load a specific part of the webapp: https://example.com/app/#/secure/content/alarm-base/alarm-list//alarm-detail/1381122 The delegate methods are not called, although the webview loads the url successfully. The delegate methods are also called if I load the specific url directly on startup. The web appication is written in AngularJS.

I would like for the delegate handlers to trigger for every request I load from the code. Any idea on how to achieve this?

Upvotes: 1

Views: 309

Answers (1)

Smorka
Smorka

Reputation: 1129

I am not sure what is going on, but it is possible to force it to use the delegate by adding the following code when doing the request:

webView.load(request) 
webView.stopLoading() 
webView.reload()

It is clunky, but it solves the problem for me.

Upvotes: 0

Related Questions