// // RQCustomWebViewViewController.m // RQCommon // // Created by 张嵘 on 2018/11/27. // Copyright © 2018 张嵘. All rights reserved. // #import "RQCustomWebViewViewController.h" #import "WKWebViewJavascriptBridge.h" #import //#import "faceView.h" //#import "UIView+ITTAdditions.h" //#import "OliveappLivenessDetectionViewController.h" //#import "OliveappCameraPreviewController.h" //#import "OliveappDetectedFrame.h" //#import //#import "OliveappIdcardCaptorViewController.h" //#import "OliveappBase64Helper.h" //#import "OliveappImageUtility.h" @interface RQCustomWebViewViewController () /**/ /// webView @property (nonatomic, weak, readwrite) WKWebView *webView; /// 进度条 @property (nonatomic, readwrite, strong) UIProgressView *progressView; /// 返回按钮 @property (nonatomic, readwrite, strong) UIBarButtonItem *backItem; /// 关闭按钮 (点击关闭按钮 退出WebView) @property (nonatomic, readwrite, strong) UIBarButtonItem *closeItem; @property (nonatomic, strong, readwrite) WKWebViewJavascriptBridge *bridge; @property (nonatomic, copy) WVJBResponseCallback imgCallBack; @property (nonatomic, assign) BOOL isLoad; @end @implementation RQCustomWebViewViewController - (void)dealloc { /// remove observer ,otherwise will crash [_webView stopLoading]; _isLoad = NO; } - (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; @weakify(self) [self.navigationController.navigationBar setHidden:_webType == WebTypeEDU]; NSString *encodedString = (NSString*) CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)self.url,(CFStringRef)@"!$&'()*+,-./:;=?@_~%#[]",NULL, kCFStringEncodingUTF8)); NSURL *httpUrl = [NSURL URLWithString:encodedString]; if (!_isLoad) { /// 加载请求数据 [self.view addSubview:self.progressView]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:httpUrl]; if (self.bodyDicArr && self.bodyDicArr.count > 0) { // 请求方式为POST请求 [request setHTTPMethod:@"POST"]; [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; NSMutableString *bodyString = [NSMutableString string]; [[self.bodyDicArr.rac_sequence.signal deliverOnMainThread] subscribeNext:^(NSDictionary *dic) { @strongify(self) if ([self.bodyDicArr indexOfObject:dic] == 0) { [bodyString appendString:[NSString stringWithFormat:@"%@=%@",dic[@"key"],dic[@"value"]]]; } else { [bodyString appendString:[NSString stringWithFormat:@"&%@=%@",dic[@"key"],dic[@"value"]]]; } } completed:^{ @strongify(self) [request setHTTPBody:[bodyString.copy dataUsingEncoding:NSUTF8StringEncoding]]; [self.webView loadRequest:request]; }]; } else { // [request addValue:@"fj.jppt.com.cn://" forHTTPHeaderField:@"Referer"]; [self.webView loadRequest:request]; } } } - (void)viewWillDisappear:(BOOL)animated { [super viewWillDisappear:animated]; [self.progressView removeFromSuperview]; [self.navigationController.navigationBar setHidden:NO]; } - (void)viewDidLoad { [super viewDidLoad]; @weakify(self) self.navigationItem.leftBarButtonItem = self.backItem; self.navigationItem.rightBarButtonItem = self.closeItem; ///RQ-MARK FIXED: 切记 lightempty_ios 是前端跟H5商量的结果,请勿修改。 NSString *userAgent = @""; if (!(([[[UIDevice currentDevice] systemVersion] floatValue]) >= 9.0)) [[NSUserDefaults standardUserDefaults] registerDefaults:@{@"userAgent":userAgent}]; /// 注册JS WKUserContentController *userContentController = [[WKUserContentController alloc] init]; /// 这里可以注册JS的处理 涉及公司私有方法 这里笔者不作处理 WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init]; configuration.allowsInlineMediaPlayback = YES; if (@available(iOS 10.0, *)) { configuration.mediaTypesRequiringUserActionForPlayback = WKAudiovisualMediaTypeNone; } NSMutableString *jsString = [NSMutableString string]; /// 自适应屏幕宽度 [jsString appendString:@"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);"]; /// 禁止长按 [jsString appendString:@"document.documentElement.style.webkitTouchCallout='none';"]; /// 禁止选择 [jsString appendString:@"document.documentElement.style.webkitUserSelect='none';"]; /// 关闭H5的缩放手势 [jsString appendString:@"var script = document.createElement('meta');" "script.name = 'viewport';" "script.content=\"width=device-width, initial-scale=1.0,maximum-scale=1.0, minimum-scale=1.0, user-scalable=no\";" "document.getElementsByTagName('head')[0].appendChild(script);"]; WKUserScript *userScript = [[WKUserScript alloc] initWithSource:jsString injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES]; /// 添加屏幕js调用的方法 [userContentController addUserScript:userScript]; /// 赋值userContentController configuration.userContentController = userContentController; WKWebView *webView; switch (_webType) { case WebTypeEDU: { webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, SL_TopNavigationBarHeight, RQ_SCREEN_WIDTH, RQ_SCREEN_HEIGHT - SL_TopNavigationBarHeight) configuration:configuration]; break; } case WebTypeStuProtocol: { webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, RQ_SCREEN_WIDTH, RQ_SCREEN_HEIGHT - SL_TopNavigationBarHeight) configuration:configuration]; break; } default: { webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, RQ_SCREEN_WIDTH, RQ_SCREEN_HEIGHT - kNavOffSet - kSafeAreaBottomHeight) configuration:configuration]; break; } } webView.navigationDelegate = self; webView.UIDelegate = self; if (@available(iOS 9.0, *)) { webView.customUserAgent = userAgent; } else { // Fallback on earlier versions } self.webView = webView; [self.view addSubview:webView]; // 开启日志,方便调试 [WKWebViewJavascriptBridge enableLogging]; // 给哪个webview建立JS与OjbC的沟通桥梁 _bridge = [WKWebViewJavascriptBridge bridgeForWebView:self.webView]; [_bridge setWebViewDelegate:self]; // OC端通过responseCallback回调JS端,JS就可以得到所需要的数据 [self.bridge registerHandler:@"closeWindows" handler:^(id data, WVJBResponseCallback responseCallback) { @strongify(self) if (responseCallback) { // 反馈给JS // responseCallback(@{@"userId": @"123456"}); UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"退出" message:@"确定退出在线学习吗?" preferredStyle:UIAlertControllerStyleAlert]; UIAlertAction *saveAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { @strongify(self) responseCallback(@"1"); // 开启返回手势 if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) { self.navigationController.interactivePopGestureRecognizer.enabled = YES; } [self.navigationController popViewControllerAnimated:YES]; }]; [alert addAction:saveAction]; WKBackForwardListItem *item = self.webView.backForwardList.currentItem; NSLog(@"-----%@------",[item.URL.absoluteString componentsSeparatedByString:@"/"].lastObject); if ([[item.URL.absoluteString componentsSeparatedByString:@"/"].lastObject isEqualToString:@"plan"]) { UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) { responseCallback(@"0"); }]; [alert addAction:cancleAction]; } [self presentViewController:alert animated:YES completion:nil]; } }]; [self.bridge registerHandler:@"closeH5" handler:^(id data, WVJBResponseCallback responseCallback) { @strongify(self) if (responseCallback) { // 反馈给JS // responseCallback(@{@"userId": @"123456"}); UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"退出" message:@"确定退出在线学习吗?" preferredStyle:UIAlertControllerStyleAlert]; UIAlertAction *saveAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { @strongify(self) responseCallback(@"1"); // 开启返回手势 if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) { self.navigationController.interactivePopGestureRecognizer.enabled = YES; } [self.navigationController popViewControllerAnimated:YES]; }]; [alert addAction:saveAction]; WKBackForwardListItem *item = self.webView.backForwardList.currentItem; NSLog(@"-----%@------",[item.URL.absoluteString componentsSeparatedByString:@"/"].lastObject); if (![self.webView.URL.absoluteString containsString:@"http://lncx.anjia365.com"] || ([self.webView.URL.absoluteString containsString:@"http://lncx.anjia365.com"] && [[item.URL.absoluteString componentsSeparatedByString:@"/"].lastObject isEqualToString:@"plan"])) { UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) { responseCallback(@"0"); }]; [alert addAction:cancleAction]; } [self presentViewController:alert animated:YES completion:nil]; } }]; [_bridge registerHandler:@"photoClick" handler:^(id data, WVJBResponseCallback responseCallback) { @strongify(self) if (responseCallback) { self.imgCallBack = responseCallback; } // FaceStreamDetectorViewController *faceVC = [[FaceStreamDetectorViewController alloc]init]; // faceVC.faceDelegate = self; // faceVC.modalPresentationStyle = UIModalPresentationFullScreen; // [self presentViewController:faceVC animated:YES completion:^{ // // }]; [self postuploadPhotoLog]; self.hidesBottomBarWhenPushed = YES; // [self checkBodyInfo]; }]; /// oc调用js [webView evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id result, NSError *error) { NSLog(@"navigator.userAgent.result is ++++ %@", result); }]; /// 监听数据 [RACObserve(self.webView, title) subscribeNext:^(NSString *titleStr) { @strongify(self); NSLog(@"%@",titleStr); /// CoderMikeHe FIXED: 这里只设置导航栏的title 以免self.title 设置了tabBarItem.title switch (self.webType) { case WebTypeStuProtocol: { self.navigationItem.title = @"学员报名合同"; break; } default: { self.navigationItem.title = self.webView.title; break; } } }]; [RACObserve(self.webView, loading) subscribeNext:^(NSNumber *currentLoadingState) { BOOL isLoading = [currentLoadingState boolValue]; if (isLoading) { [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES]; NSLog(@"--- webView is loading ---"); }else { NSLog(@"--- webView isn't loading ---"); [MBProgressHUD hideHUDForView:[UIApplication sharedApplication].keyWindow animated:YES]; } }]; [RACObserve(self.webView, estimatedProgress) subscribeNext:^(NSNumber *estimatedProgressValue) { NSLog(@"%@",estimatedProgressValue); @strongify(self); [self.progressView setAlpha:1.0f]; [self.progressView setProgress:self.webView.estimatedProgress animated:YES]; if(self.webView.estimatedProgress >= 1.0f) { [UIView animateWithDuration:0.3 delay:0.3 options:UIViewAnimationOptionCurveEaseOut animations:^{ @strongify(self) [self.progressView setAlpha:0.0f]; } completion:^(BOOL finished) { @strongify(self) [self.progressView setProgress:0.0f animated:NO]; self.isLoad = YES; }]; } }]; //监听UIWindow隐藏 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(endFullScreen) name:UIWindowDidBecomeHiddenNotification object:nil]; /// 添加刷新控件 // if(self.viewModel.shouldPullDownToRefresh){ // [self.webView.scrollView rq_addHeaderRefresh:^(MJRefreshNormalHeader *header) { // @strongify(self); // [self.webView reload]; // }]; // [self.webView.scrollView.mj_header beginRefreshing]; // } self.webView.scrollView.contentInset = self.contentInset; /// RQ-MARK: 适配 iPhone X + iOS 11,去掉安全区域 if (@available(iOS 11.0, *)) { RQAdjustsScrollViewInsets_Never(webView.scrollView); } } - (void)viewDidAppear:(BOOL)animated { [super viewDidAppear:animated]; switch (_webType) { case WebTypeAd: { /// http://liferestart.syaro.io/view/ NSLog(@"%@",self.webView.URL.host); if ([self.webView.URL.host isEqualToString:@"liferestart.syaro.io"] ) { [RQ_AD_MANAGER loadAdWithAdType:RQADType_Interstitial customView:self.webView]; } break; } default: break; } } - (void)endFullScreen { [self prefersStatusBarHidden]; } //- (void)sendFaceImage:(UIImage *)faceImage { // NSLog(@"-----------------------%@------%@",self.webView.URL.absoluteString,[self.webView.URL.absoluteString containsString:@"http://lncx.anjia365.com"]? @"YES" : @"NO"); // UIImage *normalImage = [UIImage fixOrientation:faceImage]; // /// 通安 // if ([self.webView.URL.absoluteString containsString:@"http://lncx.anjia365.com"]) { // normalImage = [UIImage imageWithCGImage:normalImage.CGImage // scale:normalImage.scale // orientation:UIImageOrientationDown]; // } // NSData *imgData = UIImageJPEGRepresentation(normalImage, .2f); // NSString *backString = [NSString stringWithFormat:@"data:image/jpeg;base64,%@",[OliveappBase64Helper encode:imgData]]; // @weakify(self); // if (self.imgCallBack) { // @strongify(self); // [MBProgressHUD showHUDAddedTo:self.view animated:YES]; // dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ // self.imgCallBack(backString); // [MBProgressHUD hideHUDForView:self.view animated:YES]; // }); // } //} // //- (void)sendFaceImageError { // //} //base64encode then urlencode (采用这个方法,一步到位) - (NSString *)base64AndUrlencodeStringFromData: (NSData *)data { NSString *base64String = [data base64EncodedStringWithOptions:0]; NSString *encodedString = (NSString *) CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)base64String, NULL, (CFStringRef)@"!*'();:@&=+$,/?%#[]", kCFStringEncodingUTF8)); return encodedString; } //// 活体检测 //- (void)checkBodyInfo{ // UIStoryboard * board = [UIStoryboard storyboardWithName:@"LivenessDetection" bundle:nil]; // OliveappLivenessDetectionViewController * livenessDetectionViewController; // livenessDetectionViewController = (OliveappLivenessDetectionViewController *)[ board instantiateViewControllerWithIdentifier:@"LivenessDetectionStoryboard"]; // livenessDetectionViewController.modalPresentationStyle = 0; // livenessDetectionViewController.faceDelegate = self; // NSError *error; // BOOL isSuccess = [livenessDetectionViewController setConfigLivenessDetection:self withError: &error]; // if (isSuccess){ //// [self.navigationController pushViewController:livenessDetectionViewController animated:YES]; // [self presentViewController:livenessDetectionViewController animated:YES completion:^{ // // }]; // } //} //- (void)onLivenessSuccess:(OliveappDetectedFrame *)detectedFrame{ // dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ // [self dismissViewControllerAnimated:NO completion:nil]; //// if (self.imgCallBack) { //// NSMutableData *datas = detectedFrame.verificationData.mutableCopy; //// NSData *adata = [[NSData alloc] initWithBytes:detectedFrame.verificationData.bytes length:detectedFrame.verificationData.length]; //// NSString * str =[self base64AndUrlencodeStringFromData:datas]; //// //// UIImage *iamge0 = [UIImage imageWithData:[datas subdataWithRange:NSMakeRange(8, datas.length - 8)]]; //// //// //// UIImage *image = [UIImage imageWithData:datas]; //// UIImage *image1 = [UIImage imageWithData:adata]; //// UIImage *image2 = [OliveappImageUtility convertBitmapRGBA8ToUIImage:(unsigned char *)detectedFrame.verificationData.bytes withWidth:100 withHeight:100]; //// //// NSString *backString = [OliveappBase64Helper encode:datas]; //// NSString *backString1 = [NSString stringWithFormat:@"data:image/jpeg;base64,%@",str]; //// self.imgCallBack(backString1); //// } //// [self.navigationController popViewControllerAnimated:YES]; // }); //} // //- (void)onLivenessFail:(int)sessionState withDetectedFrame:(OliveappDetectedFrame *)detectedFrame{ // // dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ // [self dismissViewControllerAnimated:NO completion:nil]; // UIAlertController *actionsheet = [UIAlertController alertControllerWithTitle:@"提示" message:@"活体检测失败,是否重新进行活体检测" preferredStyle:UIAlertControllerStyleAlert]; // // UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"是" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { // [self checkBodyInfo]; // }]; // // UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"否" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) { // }]; // [actionsheet addAction:action1]; // [actionsheet addAction:action2]; // // [self presentViewController:actionsheet animated:YES completion:nil]; // }); //} // //- (void)onLivenessCancel{ // dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ // [self dismissViewControllerAnimated:NO completion:nil]; // }); //} #pragma mark - 事件处理 - (void)_backItemDidClicked{ /// 返回按钮事件处理 /// 可以返回到上一个网页,就返回到上一个网页 if (self.webView.canGoBack) { [self.webView goBack]; } else {/// 不能返回上一个网页,就返回到上一个界面 NSArray *viewcontrollers = self.navigationController.viewControllers; if(viewcontrollers.count>1) { if([viewcontrollers objectAtIndex:viewcontrollers.count-1] == self) { //push方式 [self.navigationController popViewControllerAnimated:YES]; } } else { //present方式 [self.navigationController dismissViewControllerAnimated:NO completion:NULL]; } } } - (void)_closeItemDidClicked{ /// 判断 是Push还是Present进来的 [self.navigationController dismissViewControllerAnimated:NO completion:NULL]; } - (UIEdgeInsets)contentInset { return UIEdgeInsetsMake(0, 0, 0, 0); } #pragma mark - WKScriptMessageHandler - (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{ /// js call OC function } #pragma mark - WKNavigationDelegate /// 内容开始返回时调用 - (void)webView:(WKWebView *)webView didCommitNavigation:(null_unspecified WKNavigation *)navigation { UIBarButtonItem *backItem = self.navigationItem.leftBarButtonItems.firstObject; if (backItem) { if ([self.webView canGoBack]) { [self.navigationItem setLeftBarButtonItems:@[backItem, self.closeItem]]; } else { [self.navigationItem setLeftBarButtonItems:@[backItem]]; } } } - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{ if (navigationType==UIWebViewNavigationTypeBackForward) { self.webView.canGoBack?[self.webView goBack]:[self.navigationController popViewControllerAnimated:YES]; } return YES; } // 导航完成时,会回调(也就是页面载入完成了) - (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation { // if (self.viewModel.shouldPullDownToRefresh) [webView.scrollView.mj_header endRefreshing]; // 禁用返回手势 if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) { self.navigationController.interactivePopGestureRecognizer.enabled = NO; } } // 导航失败时会回调 - (void)webView:(WKWebView *)webView didFailNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error { // if (self.viewModel.shouldPullDownToRefresh) [webView.scrollView.mj_header endRefreshing]; // 开启返回手势 if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) { self.navigationController.interactivePopGestureRecognizer.enabled = YES; } } // 在发送请求之前,决定是否跳转 - (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler { NSLog(@"navigationAction.request.URL: %@", navigationAction.request.URL); WKNavigationActionPolicy actionPolicy = WKNavigationActionPolicyAllow;//允许 NSString *urlString = [[navigationAction.request URL] absoluteString]; // urlString = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLUserAllowedCharacterSet]]; // urlString = [[urlString mj_url] absoluteString]; // urlString = [urlString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; NSLog(@"跳转:>>>???>>%@",urlString); // // 拦截WKWebView加载的微信支付统一下单链接, 将redirect_url参数修改为唤起自己App的URLScheme if ([urlString hasPrefix:@"https://wx.tenpay.com/cgi-bin/mmpayweb-bin/checkmweb"] && ![urlString hasSuffix:[NSString stringWithFormat:@"&redirect_url=https://fj.jppt.com.cn/"]]) { // decisionHandler(WKNavigationActionPolicyCancel); // NSString *redirectUrl = nil; // if ([urlString containsString:@"redirect_url="]) { // NSRange redirectRange = [urlString rangeOfString:@"redirect_url"]; // redirectUrl = [[urlString substringToIndex:redirectRange.location] stringByAppendingString:[NSString stringWithFormat:@"&redirect_url=https://fj.jppt.com.cn/"]]; // } else { //// if ([urlString containsString:@"refer_page_name"]) { //// urlString = [urlString componentsSeparatedByString:@"refer_page_name"].firstObject; //// } // redirectUrl = [urlString stringByAppendingString:[NSString stringWithFormat:@"&redirect_url=https://fj.jppt.com.cn/"]]; // } // NSMutableURLRequest *newRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:redirectUrl] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30]; // newRequest.allHTTPHeaderFields = navigationAction.request.allHTTPHeaderFields; // newRequest.URL = [NSURL URLWithString:redirectUrl]; // [webView loadRequest:newRequest]; // return; } //打开微信 if([urlString containsString:@"weixin://wap/pay?"]) { actionPolicy =WKNavigationActionPolicyCancel;//不允许跳转 NSURL*url = [NSURL URLWithString:urlString]; if([[UIApplication sharedApplication] respondsToSelector:@selector(openURL:options:completionHandler:)]) { [[UIApplication sharedApplication] openURL:url options:@{UIApplicationOpenURLOptionUniversalLinksOnly: @NO} completionHandler:^(BOOL success) { }]; }else{ [[UIApplication sharedApplication]openURL:webView.URL]; } } if ([navigationAction.request.URL.host isEqualToString:@"mclient.alipay.com"]) { // __weak APWebViewController* wself = self; NSString * urlStr = navigationAction.request.URL.absoluteString; NSString * returnUrlStr = [urlStr componentsSeparatedByString:@"&return_url="].lastObject; BOOL isIntercepted = [[AlipaySDK defaultService] payInterceptorWithUrl:urlStr fromScheme:@"JSJPStudent" callback:^(NSDictionary *result) { // 处理支付结果 NSLog(@"%@", result); // 返回码,标识支付状态,含义如下: // 9000——订单支付成功 // 8000——正在处理中 // 4000——订单支付失败 // 5000——重复请求 // 6001——用户中途取消 // 6002——网络连接出错 // isProcessUrlPay 代表 支付宝已经处理该URL if ([result[@"isProcessUrlPay"] boolValue]) { // returnUrl 代表 第三方App需要跳转的成功页URL NSString *urlStr = result[@"returnUrl"]; NSString *resultCode = result[@"resultCode"]; if ([resultCode integerValue] == 9000) { // TO DO 加载urlStr NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlStr]]; [webView loadRequest:request]; } else if([resultCode integerValue] == 6001){ // TO DO 自己的业务逻辑 urlStr是空的 [webView reload]; } } }]; if (isIntercepted) { decisionHandler(WKNavigationActionPolicyCancel); return; } else{ decisionHandler(WKNavigationActionPolicyAllow); return; } } decisionHandler(actionPolicy); } - (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler { decisionHandler(WKNavigationResponsePolicyAllow); } - (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *__nullable credential))completionHandler { NSURLCredential *cred = [[NSURLCredential alloc] initWithTrust:challenge.protectionSpace.serverTrust]; completionHandler(NSURLSessionAuthChallengeUseCredential, cred); } #pragma mark - WKUIDelegate - (nullable WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures { /// CoderMike Fixed : 解决点击网页的链接 不跳转的Bug。 WKFrameInfo *frameInfo = navigationAction.targetFrame; if (![frameInfo isMainFrame]) { [webView loadRequest:navigationAction.request]; } return nil; } #pragma mark runJavaScript - (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler { // [NSObject rq_showAlertViewWithTitle:nil message:message confirmTitle:@"我知道了"]; completionHandler(); } - (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL result))completionHandler { completionHandler(YES); } - (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(nullable NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * __nullable result))completionHandler { completionHandler(defaultText); } #pragma mark - Getter & Setter - (UIProgressView *)progressView { if (!_progressView) { CGFloat progressViewW = ([[UIScreen mainScreen] bounds].size.width); CGFloat progressViewH = 3; CGFloat progressViewX = 0; CGFloat progressViewY = 0; UIProgressView *progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(progressViewX, progressViewY, progressViewW, progressViewH)]; progressView.progressTintColor = [UIColor colorWithRed:(253 / 255.0) green:(103 / 255.0) blue:(27 / 255.0) alpha:1]; progressView.trackTintColor = [UIColor clearColor]; [self.view addSubview:progressView]; self.progressView = progressView; } return _progressView; } - (UIBarButtonItem *)backItem { if (_backItem == nil) { _backItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"backIcon.png"] style:UIBarButtonItemStylePlain target:self action:@selector(_backItemDidClicked)]; self.navigationController.navigationBar.translucent = NO; [self.navigationItem setLeftBarButtonItem:_backItem]; } return _backItem; } - (UIBarButtonItem *)closeItem { if (!_closeItem) { _closeItem = [UIBarButtonItem rq_systemItemWithTitle:@"关闭" titleColor:RQ_MAIN_COLOR imageName:nil target:self selector:@selector(_closeItemDidClicked) textType:YES]; } return _closeItem; } - (void)postuploadPhotoLog { // if (![Util connectedToNetWork]) { // showMsgUnconnect(); // return; // } NSMutableArray *aArray=[NSMutableArray array]; [aArray addPro:@"idcard" Value:[NSString stringWithFormat:@"%@",RQ_USER_MANAGER.currentUser.loginCode]]; [aArray addPro:@"outid" Value:[NSString stringWithFormat:@"%@",RQ_USER_MANAGER.currentUser.outId]]; NSString* method = @"uploadPhotoLog"; [jiaPeiManager requestAnythingWithURL:method array:aArray data:nil completion:^(NSDictionary *root) { // if (!root) { // ShowMsgFailed(); // return ; // } // // if ([root[@"code"] isEqualToString:@"0"]) { // // } else { //// ShowMsg(root[@"msg"]); // return ; // } }]; } @end