检测何时在WKWebView中单击链接

Ber*_*lue 10 objective-c ios wkwebview

如何检测WKWebView中单击链接的时间?我在UIWebView中寻找相当于此的东西.

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    if(navigationType == UIWebViewNavigationTypeLinkClicked)
    {

    }
    return YES;
}
Run Code Online (Sandbox Code Playgroud)

我试过这个,WKNavigationDelegateWKNavigationTypeOther即使点击链接,我也只能得到所有请求.

- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
{
    if(navigationAction.navigationType == WKNavigationTypeLinkActivated)
    {

    }
    decisionHandler(WKNavigationActionPolicyAllow);
}
Run Code Online (Sandbox Code Playgroud)

Cat*_* T. 6

您可以在WkWebView中执行以下操作:

override func viewDidLoad() {
    super.viewDidLoad()

     let webView = WKWebView()
     self.view.addSubview(webView) // you need to also setup constraints here - I left out for clarity
     // Make sure you set the delegate, so you get the callback
     self.webView.navigationDelegate = self
}

 // WKWebViewNavigationDelegate
 func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
     guard let url = navigationAction.request.url, let scheme = url.scheme, scheme.contains("http") else {
            // This is not HTTP link - can be a local file or a mailto
            decisionHandler(.cancel)
            return
        }
     // This is a HTTP link
     open(url: url)
     decisionHandler(.allow)
}
Run Code Online (Sandbox Code Playgroud)

在此委托方法中,您将获取WKWebView尝试打开的URL请求。您可以在此处检查的属性URLRequest并做出相应的响应。

您甚至可以为URLRequest处理该逻辑编写扩展,以便您可以重用它。

extension URLRequest {
    var isHttpLink: Bool {
        return self.url?.scheme?.contains("http") ?? false
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,您可以将委托方法中的long条件更改为:

 // WKWebViewNavigationDelegate
 func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
   guard navigationAction.request.isHttpLink else {
        decisionHandler(.allow)
        return
    }
   // ... handle url
Run Code Online (Sandbox Code Playgroud)