WKWebview 不能打开第三方APP
2018-01-25 本文已影响953人
xiao小马哥
把UIWebview
更换为WKWebview
之后发现不能跳转到第三方应用(JD),以前判断的方法就在代理方法做拦截,
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
NSURL *url = [request URL];
/// 这个是京东的协议头,判断能否打开,能打开返回NO
if ([url.absoluteString hasPrefix:@"openapp"]) {
if([[UIApplication sharedApplication]canOpenURL:url])
{
[[UIApplication sharedApplication]openURL:url];
return NO;
}
}
现在更换WKWebview
后里面的判断逻辑都放在这个方法里
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler{
NSURL *url = [navigationResponse.response URL];
if ([url.absoluteString hasPrefix:@"openapp"]) {
if([[UIApplication sharedApplication]canOpenURL:url])
{
[[UIApplication sharedApplication]openURL:url];
decisionHandler(WKNavigationResponsePolicyCancel);
return;
}
}
经过测试发现,JD的请求里面没有openapp
的协议头,也就导致无法打开JD,是因为decidePolicyForNavigationResponse
这个方法里面返回的是请求之后的结果,我们要在请求之前取到结果,那就需要另一个代理方法
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
if ([navigationAction.request.URL.scheme containsString:@"openapp"]){
if([[UIApplication sharedApplication]canOpenURL:navigationAction.request.URL])
{
[[UIApplication sharedApplication]openURL:navigationAction.request.URL];
decisionHandler(WKNavigationActionPolicyCancel);
}else{
decisionHandler(WKNavigationActionPolicyAllow);
}
}else{
decisionHandler(WKNavigationActionPolicyAllow);
}
}
这个方法是将要加载请求,可以拦截所有的请求信息!