Home > front end >  WKWebView Navigation Delegate Not Called
WKWebView Navigation Delegate Not Called

Time:12-19

I am having difficulty getting a WKWebview to call its delegate methods, namely the did finish one.

I am attempting something similar to this post generating a pdf report using html loaded into a WKWebView;

WKWebView not calling navigation delegate methods

However trying the suggestion there, that doesn't work for me. I have a WKWebView made in a separate class to the View controller that will be calling its methods.

If I strip things right down and just try to simply load a website in the WebView to see if the delegate functions get called I get nothing.

Here is my test class;

import UIKit
import WebKit

class TestWebview: NSObject {

let webView = WKWebView ()

func loadWebsite () {
    
    print ("LOAD TEST CALLED")

    webView.navigationDelegate = self
    
    let link = URL(string: "https://www.apple.com")!
    
    let request = URLRequest(url: link)
    
    webView.load(request)
    
 }

}

extension TestWebview: WKNavigationDelegate {


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

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


}

And here is how I am calling it in a separate view controller;

override func viewDidLoad() {

super.viewDidLoad()

  let test = TestWebview ()
  
  test.loadWebsite()

 }

Although if I put a WKWebView as an outlet into a view controller using Storyboards then the delegate methods do get called. I am trying to avoid this however as I don't want to see a web view in the view controller and want to keep all the code for that separate in another class.

Am I missing something? Checking various other posts on Stack Overflow about this hasn't given me any solutions other than making sure the navigation delegate is being set, which I am. Any help would be greatly appreciated.

CodePudding user response:

You need to move let test = TestWebview () to class level, otherwise this object is going to be evicted when viewDidLoad completes: the navigationDelegate is defined as weak, so it's not going to prevent it either.

  • Related