ios – 检测在WKWebView中单击链接的时间

前端之家收集整理的这篇文章主要介绍了ios – 检测在WKWebView中单击链接的时间前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如何检测WKWebView中单击链接的时间?我在UIWebView中寻找相当于此的东西.
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    if(navigationType == UIWebViewNavigationTypeLinkClicked)
    {

    }
    return YES;
}

我在WKNavigationDelegate中尝试了这个,但即使单击链接,我也只能获得所有请求的WKNavigationTypeOther.

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

    }
    decisionHandler(WKNavigationActionPolicyAllow);
}

解决方法

您可以在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)
}

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

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

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

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

// WKWebViewNavigationDelegate
 func webView(_ webView: WKWebView,decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
   guard navigationAction.request.isHttpLink else {
        decisionHandler(.allow)
        return
    }
   // ... handle url
原文链接:https://www.f2er.com/iOS/333755.html

猜你在找的iOS相关文章