如何在传递给另一个的 WKWebView 上使用 didFinish 导航 class

How to use didFinish navigation on an WKWebView passed to another class

我正在设置一个应用程序,其中 WKWebView 对象是在一个 class 中创建的,然后传递给另一个 class 进行处理,但是当我使用 didFinish navigation 在第二个 class 中,它永远不会被调用。

我添加了WKNavigationDelegate协议,并设置了navigationDelegate = self

class one: UIViewController {
   var webView: WKWebView = WKWebView();

    override func viewDidLoad(){
      var second = Second()
      second.web = webView;
      second.test()
   } 
}

class second: NSObject, WKNavigationDelegate {
  var web: WKWebView? = nil;

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

  func test(){
     self.web!.load(URLRequest(url: URL(string: "https://google.com")!))
  }
}

我从未看到 "Test" 消息。

将其设为实例变量以保留对象,以便调用委托

var second = Second() /// << here

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

func test(){ 
   self.web!.navigationDelegate = self
   self.web!.load(URLRequest(url: URL(string: "https://google.com")!)) 
}
import UIKit
import WebKit

class WKWebViewController: UIViewController, WKNavigationDelegate {

    @IBOutlet weak var webWK: WKWebView!
    @IBOutlet weak var activityIndi: UIActivityIndicatorView!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.

        webWK.navigationDelegate = self
        let appStoreURL = URL(string: "https://google.com")
        webWK.load(URLRequest(url: appStoreURL!))
    }

    func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
        activityIndi.startAnimating()
    }

    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        activityIndi.stopAnimating()
    }

}