对我来说,使用 decidePolicyFor 导航委托的方法不起作用。
因为WKNavigationDelegate的方法没用
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void)
只有在整个页面重新加载时才会被调用。
为了能够捕获所有 WKWebView 的请求 URL 更改,必须在 WKWebView 的 URL 属性上放置一个 Key-Value 观察器。
首先,在viewDidLoad中添加:
webView.addObserver(self, forKeyPath: "URL", options: .new, context: nil)
其次,添加observeValue方法
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == #keyPath(WKWebView.url) {
// Whenever URL changes, it can be accessed via WKWebView instance
let url = webView.url
}
}