app中有个按钮,点击跳转到网页进行支付
_webView = [[WKWebViewalloc] initWithFrame:CGRectMake(0, kStatusBarHeight,SCREEN_WIDTH,SCREEN_HEIGHT-kStatusBarHeight -HitoSafeAreaHeight)];
[_webViewsetNavigationDelegate:self];
_webView.scrollView.delegate =self;
[_webViewsizeToFit];
_webView.UIDelegate =self;
[self.view addSubview:_webView];
[_webView addObserver:selfforKeyPath:@"estimatedProgress"options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil];
webRequest = [NSMutableURLRequest requestWithURL:requestUrl cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
[webRequest setHTTPMethod:@"GET"];
if(self.IsPay) {//如果是支付界面,支付这里要设置
[webRequest setValue:@"www.maxxiang.com"forHTTPHeaderField:@"Referer"];
}
[_webView loadRequest:webRequest];
设置[_webView setNavigationDelegate:self];
然后每次加载会走下面代理方法
- (void)webView:(WKWebView*)webView decidePolicyForNavigationAction:(WKNavigationAction*)navigationAction decisionHandler:(void(^)(WKNavigationActionPolicy))decisionHandler {
NSString*urlString = [[navigationAction.requestURL]absoluteString];
urlString = [urlStringstringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
if([urlStringcontainsString:@"weixin://wap/pay?"]) {
decisionHandler(WKNavigationActionPolicyCancel);
//解决wkwebview weixin://无法打开微信客户端的处理
NSURL*url = [NSURLURLWithString:urlString];
[[UIApplication sharedApplication]openURL:url options:@{UIApplicationOpenURLOptionUniversalLinksOnly: @NO} completionHandler:^(BOOL success) {
}];
}else{
decisionHandler(WKNavigationActionPolicyAllow);
}
}
注意 decisionHandler 一个流程下来只能走一次,百度里面很多例子都是直接
- (void)webView:(WKWebView*)webView decidePolicyForNavigationAction:(WKNavigationAction*)navigationAction decisionHandler:(void(^)(WKNavigationActionPolicy))decisionHandler {
NSString*urlString = [[navigationAction.requestURL]absoluteString];
urlString = [urlStringstringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
if([urlStringcontainsString:@"weixin://wap/pay?"]) {
decisionHandler(WKNavigationActionPolicyCancel);
//解决wkwebview weixin://无法打开微信客户端的处理
NSURL*url = [NSURLURLWithString:urlString];
[[UIApplication sharedApplication]openURL:url options:@{UIApplicationOpenURLOptionUniversalLinksOnly: @NO} completionHandler:^(BOOL success) {
}];
}
decisionHandler(WKNavigationActionPolicyAllow);
}
这样的话,平时加载没问题,一旦加载了支付,就会走两次decisionHandler,那样app会崩溃。。。 多走一坑