WKWebView函数用于检测URL是否已更改

Mat*_*ift 4 ios swift wkwebview

是否有WKWebView类的函数允许您检测WebView的URL何时更改?

didCommitdidStartProvisionalNavigation功能并不总是似乎与web视图中的某些元素工作时开火.

编辑:尝试添加通知观察者.这是我到目前为止所拥有的:

extension Notification.Name {
    static let checkURL = Notification.Name("checkURL")
}

NotificationCenter.default.post(name: .checkURL, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(getter: webView.url), name: .checkURL, object: webView.url)
Run Code Online (Sandbox Code Playgroud)

Ata*_*lyk 18

迅捷版

// Add observer
webView.addObserver(self, forKeyPath: "URL", options: .new, context: nil)

// Observe value
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
    if let key = change?[NSKeyValueChangeKey.newKey] {
        print("observeValue \(key)") // url value
    }
}
Run Code Online (Sandbox Code Playgroud)


haw*_*der 7

你是什​​么意思他们似乎并不总是开火?什么样的元素?他们必须为了使WkWebView能够工作.

您尝试更改URL的第一个迹象是:decisionPolicyForNavigationAction

- (void) webView: (WKWebView *) webView decidePolicyForNavigationAction: (WKNavigationAction *) navigationAction decisionHandler: (void (^)(WKNavigationActionPolicy)) decisionHandler {
    NSLog(@"%s", __PRETTY_FUNCTION__);
    decisionHandler(WKNavigationActionPolicyAllow); //Always allow
    NSURL *u1 = webView.URL;
    NSURL *u2 = navigationAction.request.URL; //If changing URLs this one will be different
}
Run Code Online (Sandbox Code Playgroud)

到达时:didStartProvisionalNavigation它已经改变了.

- (void) webView: (WKWebView *) webView didStartProvisionalNavigation: (WKNavigation *) navigation {
    NSLog(@"%s", __PRETTY_FUNCTION__);
    NSURL *u1 = webView.URL;  //By this time it's changed
}
Run Code Online (Sandbox Code Playgroud)

您所要做的就是实现这些委托方法(在Swift中)并在您看到它发生变化时执行您想要的操作.