WKWebview中打开第三方自定义url scheme

WKWebview默认是不支持打开第三自定义的url scheme,解决办法就是在页面加载的错误回调或者跳转回调里获取url手动打卡。

swift代码

func webView(webView: WKWebView, didFailNavigation navigation: WKNavigation!, withError error: NSError) {
    handleError(error)
}
 
func webView(webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: NSError) {
    handleError(error)
}
 
func handleError(error: NSError) {
    if let failingUrl = error.userInfo["NSErrorFailingURLStringKey"] as? String {
        if let url = NSURL(string: failingUrl) {
            let didOpen = UIApplication.sharedApplication().openURL(url)
            if didOpen {
                print("openURL succeeded")
                return
            }
        }
    }
}

oc代码


-(void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error;
{
    [self handleError:error];
}

// 页面加载失败时调用
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error
{
    [self handleError:error];
}

- (void)handleError:(NSError *)error
{
    NSString *url = error.userInfo[NSURLErrorFailingURLStringErrorKey].absoluteString;

if ([strRequest hasPrefix:@"weixin://"]) {
        // 拦截点击链接
//        [self handleCustomAction:strRequest];
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:strRequest]];
        // 不允许跳转
        decisionHandler(WKNavigationActionPolicyCancel);
    }else {
        // 允许跳转
        decisionHandler(WKNavigationActionPolicyAllow);
    }
}

你可能感兴趣的:(WKWebview中打开第三方自定义url scheme)