前段时间做了一个网页下载的功能,需求是这样的,点击原生页面一个按钮然后打开wkwebview,在此H5页面填写信息,点击提交按钮跳转到下一个H5页面,这个H5页面有个下载按钮,点击下载按钮没有反应。
就是这么个情况,然后先解决呗,一顿百度,找到这些资料
-(void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{ if(webView != self.webView) { decisionHandler(WKNavigationActionPolicyAllow); return; } NSURL * url = navigationAction.request.URL; UIApplication *app = [UIApplication sharedApplication]; // appstorte if ([url.absoluteString containsString:@"itunes.apple.com"]) { if ([app canOpenURL:url]) { [app openURL:url options:@{} completionHandler:^(BOOL success) { }]; decisionHandler(WKNavigationActionPolicyCancel); return; } } if (!navigationAction.targetFrame.isMainFrame) { [self.webView loadRequest:navigationAction.request]; } // appstore的外的包 if ([url.absoluteString containsString:@"itms-services://"]) { [app openURL:url options:@{} completionHandler:^(BOOL success) { }]; decisionHandler(WKNavigationActionPolicyCancel); return; } decisionHandler(WKNavigationActionPolicyAllow); }
然并卵。。。。。
但是这些资料也指出了一个解决问题的点,到下载的时候H5 链接是一定包含这个字段的 “
itms-services://
”
但是这个链接又不是一个网页,跳转不过去的,那么能不能找到这个链接前的一个H5页面呢?答案是当然可以,所以解决了
先设置属性用来保存H5地址
@property (nonatomic, copy) NSString *strWithNetURL;
wkwebview有个代理方法,这个方法是每次网页请求完才会调用,如果请求失败就不会调用,所有用来保存最后一次正常的网页再好不过
#pragma mark - 在响应完成时,调用的方法。如果设置为不允许响应,web内 容就不会传过来 - (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler{ NSLog(@"收到响应%@",navigationResponse.response.URL.absoluteString); self.strWithNetURL = navigationResponse.response.URL.absoluteString; //允许跳转 decisionHandler(WKNavigationResponsePolicyAllow); //不允许跳转 //decisionHandler(WKNavigationResponsePolicyCancel); }
然后就是设置了
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{ NSLog(@"发送请求-----》%@",navigationAction.request.URL.absoluteString); NSURL *url = navigationAction.request.URL; UIApplication *application = [UIApplication sharedApplication]; // 获得协议头(可以自定义协议头,根据协议头判断是否要执行跳转) // NSString *scheme = navigationAction.request.URL.scheme; NSString *string = navigationAction.request.URL.absoluteString; //跳转APPstrong if ([string containsString:@"itunes.apple.com"]) { [application openURL:[NSURL URLWithString:string]]; decisionHandler(WKNavigationActionPolicyCancel); return; } //跳转到Safari去下载 if ([string containsString:@"itms-services://"]) { [application openURL:[NSURL URLWithString:self.strWithNetURL]]; // 不允许web内跳转 decisionHandler(WKNavigationActionPolicyCancel); return; } // 调用电话 if ([url.scheme isEqualToString:@"tel"]) { if ([application canOpenURL:url]) { [application openURL:url]; decisionHandler(WKNavigationActionPolicyCancel); return; } } decisionHandler(WKNavigationActionPolicyAllow); }
诺,解决了