RQCustomWebViewViewController.m 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713
  1. //
  2. // RQCustomWebViewViewController.m
  3. // RQCommon
  4. //
  5. // Created by 张嵘 on 2018/11/27.
  6. // Copyright © 2018 张嵘. All rights reserved.
  7. //
  8. #import "RQCustomWebViewViewController.h"
  9. #import "WKWebViewJavascriptBridge.h"
  10. #import <AlipaySDK/AlipaySDK.h>
  11. //#import "faceView.h"
  12. //#import "UIView+ITTAdditions.h"
  13. //#import "OliveappLivenessDetectionViewController.h"
  14. //#import "OliveappCameraPreviewController.h"
  15. //#import "OliveappDetectedFrame.h"
  16. //#import <AVFoundation/AVFoundation.h>
  17. //#import "OliveappIdcardCaptorViewController.h"
  18. //#import "OliveappBase64Helper.h"
  19. //#import "OliveappImageUtility.h"
  20. @interface RQCustomWebViewViewController () /*<OliveappLivenessResultDelegate,FaceDetectorsDelegate>*/
  21. /// webView
  22. @property (nonatomic, weak, readwrite) WKWebView *webView;
  23. /// 进度条
  24. @property (nonatomic, readwrite, strong) UIProgressView *progressView;
  25. /// 返回按钮
  26. @property (nonatomic, readwrite, strong) UIBarButtonItem *backItem;
  27. /// 关闭按钮 (点击关闭按钮 退出WebView)
  28. @property (nonatomic, readwrite, strong) UIBarButtonItem *closeItem;
  29. @property (nonatomic, strong, readwrite) WKWebViewJavascriptBridge *bridge;
  30. @property (nonatomic, copy) WVJBResponseCallback imgCallBack;
  31. @property (nonatomic, assign) BOOL isLoad;
  32. @end
  33. @implementation RQCustomWebViewViewController
  34. - (void)dealloc {
  35. /// remove observer ,otherwise will crash
  36. [_webView stopLoading];
  37. _isLoad = NO;
  38. }
  39. - (void)viewWillAppear:(BOOL)animated {
  40. [super viewWillAppear:animated];
  41. @weakify(self)
  42. [self.navigationController.navigationBar setHidden:_webType == WebTypeEDU];
  43. NSString *encodedString = (NSString*) CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)self.url,(CFStringRef)@"!$&'()*+,-./:;=?@_~%#[]",NULL, kCFStringEncodingUTF8));
  44. NSURL *httpUrl = [NSURL URLWithString:encodedString];
  45. if (!_isLoad) {
  46. /// 加载请求数据
  47. [self.view addSubview:self.progressView];
  48. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:httpUrl];
  49. if (self.bodyDicArr && self.bodyDicArr.count > 0) {
  50. // 请求方式为POST请求
  51. [request setHTTPMethod:@"POST"];
  52. [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
  53. NSMutableString *bodyString = [NSMutableString string];
  54. [[self.bodyDicArr.rac_sequence.signal deliverOnMainThread] subscribeNext:^(NSDictionary *dic) {
  55. @strongify(self)
  56. if ([self.bodyDicArr indexOfObject:dic] == 0) {
  57. [bodyString appendString:[NSString stringWithFormat:@"%@=%@",dic[@"key"],dic[@"value"]]];
  58. } else {
  59. [bodyString appendString:[NSString stringWithFormat:@"&%@=%@",dic[@"key"],dic[@"value"]]];
  60. }
  61. } completed:^{
  62. @strongify(self)
  63. [request setHTTPBody:[bodyString.copy dataUsingEncoding:NSUTF8StringEncoding]];
  64. [self.webView loadRequest:request];
  65. }];
  66. } else {
  67. // [request addValue:@"fj.jppt.com.cn://" forHTTPHeaderField:@"Referer"];
  68. [self.webView loadRequest:request];
  69. }
  70. }
  71. }
  72. - (void)viewWillDisappear:(BOOL)animated {
  73. [super viewWillDisappear:animated];
  74. [self.progressView removeFromSuperview];
  75. [self.navigationController.navigationBar setHidden:NO];
  76. }
  77. - (void)viewDidLoad {
  78. [super viewDidLoad];
  79. @weakify(self)
  80. self.navigationItem.leftBarButtonItem = self.backItem;
  81. self.navigationItem.rightBarButtonItem = self.closeItem;
  82. ///RQ-MARK FIXED: 切记 lightempty_ios 是前端跟H5商量的结果,请勿修改。
  83. NSString *userAgent = @"";
  84. if (!(([[[UIDevice currentDevice] systemVersion] floatValue]) >= 9.0)) [[NSUserDefaults standardUserDefaults] registerDefaults:@{@"userAgent":userAgent}];
  85. /// 注册JS
  86. WKUserContentController *userContentController = [[WKUserContentController alloc] init];
  87. /// 这里可以注册JS的处理 涉及公司私有方法 这里笔者不作处理
  88. WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
  89. configuration.allowsInlineMediaPlayback = YES;
  90. if (@available(iOS 10.0, *)) {
  91. configuration.mediaTypesRequiringUserActionForPlayback = WKAudiovisualMediaTypeNone;
  92. }
  93. NSMutableString *jsString = [NSMutableString string];
  94. /// 自适应屏幕宽度
  95. [jsString appendString:@"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);"];
  96. /// 禁止长按
  97. [jsString appendString:@"document.documentElement.style.webkitTouchCallout='none';"];
  98. /// 禁止选择
  99. [jsString appendString:@"document.documentElement.style.webkitUserSelect='none';"];
  100. /// 关闭H5的缩放手势
  101. [jsString appendString:@"var script = document.createElement('meta');"
  102. "script.name = 'viewport';"
  103. "script.content=\"width=device-width, initial-scale=1.0,maximum-scale=1.0, minimum-scale=1.0, user-scalable=no\";"
  104. "document.getElementsByTagName('head')[0].appendChild(script);"];
  105. WKUserScript *userScript = [[WKUserScript alloc] initWithSource:jsString injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
  106. /// 添加屏幕js调用的方法
  107. [userContentController addUserScript:userScript];
  108. /// 赋值userContentController
  109. configuration.userContentController = userContentController;
  110. WKWebView *webView;
  111. switch (_webType) {
  112. case WebTypeEDU: {
  113. webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, SL_TopNavigationBarHeight, RQ_SCREEN_WIDTH, RQ_SCREEN_HEIGHT - SL_TopNavigationBarHeight) configuration:configuration];
  114. break;
  115. }
  116. case WebTypeStuProtocol: {
  117. webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, RQ_SCREEN_WIDTH, RQ_SCREEN_HEIGHT - SL_TopNavigationBarHeight) configuration:configuration];
  118. break;
  119. }
  120. default: {
  121. webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, RQ_SCREEN_WIDTH, RQ_SCREEN_HEIGHT - kNavOffSet - kSafeAreaBottomHeight) configuration:configuration];
  122. break;
  123. }
  124. }
  125. webView.navigationDelegate = self;
  126. webView.UIDelegate = self;
  127. if (@available(iOS 9.0, *)) {
  128. webView.customUserAgent = userAgent;
  129. } else {
  130. // Fallback on earlier versions
  131. }
  132. self.webView = webView;
  133. [self.view addSubview:webView];
  134. // 开启日志,方便调试
  135. [WKWebViewJavascriptBridge enableLogging];
  136. // 给哪个webview建立JS与OjbC的沟通桥梁
  137. _bridge = [WKWebViewJavascriptBridge bridgeForWebView:self.webView];
  138. [_bridge setWebViewDelegate:self];
  139. // OC端通过responseCallback回调JS端,JS就可以得到所需要的数据
  140. [self.bridge registerHandler:@"closeWindows" handler:^(id data, WVJBResponseCallback responseCallback) {
  141. @strongify(self)
  142. if (responseCallback) {
  143. // 反馈给JS
  144. // responseCallback(@{@"userId": @"123456"});
  145. UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"退出" message:@"确定退出在线学习吗?" preferredStyle:UIAlertControllerStyleAlert];
  146. UIAlertAction *saveAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
  147. @strongify(self)
  148. responseCallback(@"1");
  149. // 开启返回手势
  150. if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
  151. self.navigationController.interactivePopGestureRecognizer.enabled = YES;
  152. }
  153. [self.navigationController popViewControllerAnimated:YES];
  154. }];
  155. [alert addAction:saveAction];
  156. WKBackForwardListItem *item = self.webView.backForwardList.currentItem;
  157. NSLog(@"-----%@------",[item.URL.absoluteString componentsSeparatedByString:@"/"].lastObject);
  158. if ([[item.URL.absoluteString componentsSeparatedByString:@"/"].lastObject isEqualToString:@"plan"]) {
  159. UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
  160. responseCallback(@"0");
  161. }];
  162. [alert addAction:cancleAction];
  163. }
  164. [self presentViewController:alert animated:YES completion:nil];
  165. }
  166. }];
  167. [self.bridge registerHandler:@"closeH5" handler:^(id data, WVJBResponseCallback responseCallback) {
  168. @strongify(self)
  169. if (responseCallback) {
  170. // 反馈给JS
  171. // responseCallback(@{@"userId": @"123456"});
  172. UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"退出" message:@"确定退出在线学习吗?" preferredStyle:UIAlertControllerStyleAlert];
  173. UIAlertAction *saveAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
  174. @strongify(self)
  175. responseCallback(@"1");
  176. // 开启返回手势
  177. if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
  178. self.navigationController.interactivePopGestureRecognizer.enabled = YES;
  179. }
  180. [self.navigationController popViewControllerAnimated:YES];
  181. }];
  182. [alert addAction:saveAction];
  183. WKBackForwardListItem *item = self.webView.backForwardList.currentItem;
  184. NSLog(@"-----%@------",[item.URL.absoluteString componentsSeparatedByString:@"/"].lastObject);
  185. 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"])) {
  186. UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
  187. responseCallback(@"0");
  188. }];
  189. [alert addAction:cancleAction];
  190. }
  191. [self presentViewController:alert animated:YES completion:nil];
  192. }
  193. }];
  194. [_bridge registerHandler:@"photoClick" handler:^(id data, WVJBResponseCallback responseCallback) {
  195. @strongify(self)
  196. if (responseCallback) {
  197. self.imgCallBack = responseCallback;
  198. }
  199. // FaceStreamDetectorViewController *faceVC = [[FaceStreamDetectorViewController alloc]init];
  200. // faceVC.faceDelegate = self;
  201. // faceVC.modalPresentationStyle = UIModalPresentationFullScreen;
  202. // [self presentViewController:faceVC animated:YES completion:^{
  203. //
  204. // }];
  205. [self postuploadPhotoLog];
  206. self.hidesBottomBarWhenPushed = YES;
  207. // [self checkBodyInfo];
  208. }];
  209. /// oc调用js
  210. [webView evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id result, NSError *error) {
  211. NSLog(@"navigator.userAgent.result is ++++ %@", result);
  212. }];
  213. /// 监听数据
  214. [RACObserve(self.webView, title) subscribeNext:^(NSString *titleStr) {
  215. @strongify(self);
  216. NSLog(@"%@",titleStr);
  217. /// CoderMikeHe FIXED: 这里只设置导航栏的title 以免self.title 设置了tabBarItem.title
  218. switch (self.webType) {
  219. case WebTypeStuProtocol: {
  220. self.navigationItem.title = @"学员报名合同";
  221. break;
  222. }
  223. default: {
  224. self.navigationItem.title = self.webView.title;
  225. break;
  226. }
  227. }
  228. }];
  229. [RACObserve(self.webView, loading) subscribeNext:^(NSNumber *currentLoadingState) {
  230. BOOL isLoading = [currentLoadingState boolValue];
  231. if (isLoading) {
  232. [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
  233. NSLog(@"--- webView is loading ---");
  234. }else {
  235. NSLog(@"--- webView isn't loading ---");
  236. [MBProgressHUD hideHUDForView:[UIApplication sharedApplication].keyWindow animated:YES];
  237. }
  238. }];
  239. [RACObserve(self.webView, estimatedProgress) subscribeNext:^(NSNumber *estimatedProgressValue) {
  240. NSLog(@"%@",estimatedProgressValue);
  241. @strongify(self);
  242. [self.progressView setAlpha:1.0f];
  243. [self.progressView setProgress:self.webView.estimatedProgress animated:YES];
  244. if(self.webView.estimatedProgress >= 1.0f) {
  245. [UIView animateWithDuration:0.3 delay:0.3 options:UIViewAnimationOptionCurveEaseOut animations:^{
  246. @strongify(self)
  247. [self.progressView setAlpha:0.0f];
  248. } completion:^(BOOL finished) {
  249. @strongify(self)
  250. [self.progressView setProgress:0.0f animated:NO];
  251. self.isLoad = YES;
  252. }];
  253. }
  254. }];
  255. //监听UIWindow隐藏
  256. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(endFullScreen) name:UIWindowDidBecomeHiddenNotification object:nil];
  257. /// 添加刷新控件
  258. // if(self.viewModel.shouldPullDownToRefresh){
  259. // [self.webView.scrollView rq_addHeaderRefresh:^(MJRefreshNormalHeader *header) {
  260. // @strongify(self);
  261. // [self.webView reload];
  262. // }];
  263. // [self.webView.scrollView.mj_header beginRefreshing];
  264. // }
  265. self.webView.scrollView.contentInset = self.contentInset;
  266. /// RQ-MARK: 适配 iPhone X + iOS 11,去掉安全区域
  267. if (@available(iOS 11.0, *)) {
  268. RQAdjustsScrollViewInsets_Never(webView.scrollView);
  269. }
  270. }
  271. - (void)viewDidAppear:(BOOL)animated {
  272. [super viewDidAppear:animated];
  273. switch (_webType) {
  274. case WebTypeAd: {
  275. /// http://liferestart.syaro.io/view/
  276. NSLog(@"%@",self.webView.URL.host);
  277. if ([self.webView.URL.host isEqualToString:@"liferestart.syaro.io"] ) {
  278. [RQ_AD_MANAGER loadAdWithAdType:RQADType_Interstitial customView:self.webView];
  279. }
  280. break;
  281. }
  282. default:
  283. break;
  284. }
  285. }
  286. - (void)endFullScreen {
  287. [self prefersStatusBarHidden];
  288. }
  289. //- (void)sendFaceImage:(UIImage *)faceImage {
  290. // NSLog(@"-----------------------%@------%@",self.webView.URL.absoluteString,[self.webView.URL.absoluteString containsString:@"http://lncx.anjia365.com"]? @"YES" : @"NO");
  291. // UIImage *normalImage = [UIImage fixOrientation:faceImage];
  292. // /// 通安
  293. // if ([self.webView.URL.absoluteString containsString:@"http://lncx.anjia365.com"]) {
  294. // normalImage = [UIImage imageWithCGImage:normalImage.CGImage
  295. // scale:normalImage.scale
  296. // orientation:UIImageOrientationDown];
  297. // }
  298. // NSData *imgData = UIImageJPEGRepresentation(normalImage, .2f);
  299. // NSString *backString = [NSString stringWithFormat:@"data:image/jpeg;base64,%@",[OliveappBase64Helper encode:imgData]];
  300. // @weakify(self);
  301. // if (self.imgCallBack) {
  302. // @strongify(self);
  303. // [MBProgressHUD showHUDAddedTo:self.view animated:YES];
  304. // dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  305. // self.imgCallBack(backString);
  306. // [MBProgressHUD hideHUDForView:self.view animated:YES];
  307. // });
  308. // }
  309. //}
  310. //
  311. //- (void)sendFaceImageError {
  312. //
  313. //}
  314. //base64encode then urlencode (采用这个方法,一步到位)
  315. - (NSString *)base64AndUrlencodeStringFromData: (NSData *)data {
  316. NSString *base64String = [data base64EncodedStringWithOptions:0];
  317. NSString *encodedString = (NSString *)
  318. CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
  319. (CFStringRef)base64String,
  320. NULL,
  321. (CFStringRef)@"!*'();:@&=+$,/?%#[]",
  322. kCFStringEncodingUTF8));
  323. return encodedString;
  324. }
  325. //// 活体检测
  326. //- (void)checkBodyInfo{
  327. // UIStoryboard * board = [UIStoryboard storyboardWithName:@"LivenessDetection" bundle:nil];
  328. // OliveappLivenessDetectionViewController * livenessDetectionViewController;
  329. // livenessDetectionViewController = (OliveappLivenessDetectionViewController *)[ board instantiateViewControllerWithIdentifier:@"LivenessDetectionStoryboard"];
  330. // livenessDetectionViewController.modalPresentationStyle = 0;
  331. // livenessDetectionViewController.faceDelegate = self;
  332. // NSError *error;
  333. // BOOL isSuccess = [livenessDetectionViewController setConfigLivenessDetection:self withError: &error];
  334. // if (isSuccess){
  335. //// [self.navigationController pushViewController:livenessDetectionViewController animated:YES];
  336. // [self presentViewController:livenessDetectionViewController animated:YES completion:^{
  337. //
  338. // }];
  339. // }
  340. //}
  341. //- (void)onLivenessSuccess:(OliveappDetectedFrame *)detectedFrame{
  342. // dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  343. // [self dismissViewControllerAnimated:NO completion:nil];
  344. //// if (self.imgCallBack) {
  345. //// NSMutableData *datas = detectedFrame.verificationData.mutableCopy;
  346. //// NSData *adata = [[NSData alloc] initWithBytes:detectedFrame.verificationData.bytes length:detectedFrame.verificationData.length];
  347. //// NSString * str =[self base64AndUrlencodeStringFromData:datas];
  348. ////
  349. //// UIImage *iamge0 = [UIImage imageWithData:[datas subdataWithRange:NSMakeRange(8, datas.length - 8)]];
  350. ////
  351. ////
  352. //// UIImage *image = [UIImage imageWithData:datas];
  353. //// UIImage *image1 = [UIImage imageWithData:adata];
  354. //// UIImage *image2 = [OliveappImageUtility convertBitmapRGBA8ToUIImage:(unsigned char *)detectedFrame.verificationData.bytes withWidth:100 withHeight:100];
  355. ////
  356. //// NSString *backString = [OliveappBase64Helper encode:datas];
  357. //// NSString *backString1 = [NSString stringWithFormat:@"data:image/jpeg;base64,%@",str];
  358. //// self.imgCallBack(backString1);
  359. //// }
  360. //// [self.navigationController popViewControllerAnimated:YES];
  361. // });
  362. //}
  363. //
  364. //- (void)onLivenessFail:(int)sessionState withDetectedFrame:(OliveappDetectedFrame *)detectedFrame{
  365. //
  366. // dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  367. // [self dismissViewControllerAnimated:NO completion:nil];
  368. // UIAlertController *actionsheet = [UIAlertController alertControllerWithTitle:@"提示" message:@"活体检测失败,是否重新进行活体检测" preferredStyle:UIAlertControllerStyleAlert];
  369. //
  370. // UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"是" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
  371. // [self checkBodyInfo];
  372. // }];
  373. //
  374. // UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"否" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
  375. // }];
  376. // [actionsheet addAction:action1];
  377. // [actionsheet addAction:action2];
  378. //
  379. // [self presentViewController:actionsheet animated:YES completion:nil];
  380. // });
  381. //}
  382. //
  383. //- (void)onLivenessCancel{
  384. // dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  385. // [self dismissViewControllerAnimated:NO completion:nil];
  386. // });
  387. //}
  388. #pragma mark - 事件处理
  389. - (void)_backItemDidClicked{ /// 返回按钮事件处理
  390. /// 可以返回到上一个网页,就返回到上一个网页
  391. if (self.webView.canGoBack) {
  392. [self.webView goBack];
  393. } else {/// 不能返回上一个网页,就返回到上一个界面
  394. NSArray *viewcontrollers = self.navigationController.viewControllers;
  395. if(viewcontrollers.count>1) {
  396. if([viewcontrollers objectAtIndex:viewcontrollers.count-1] == self) {
  397. //push方式
  398. [self.navigationController popViewControllerAnimated:YES];
  399. }
  400. } else {
  401. //present方式
  402. [self.navigationController dismissViewControllerAnimated:NO completion:NULL];
  403. }
  404. }
  405. }
  406. - (void)_closeItemDidClicked{
  407. /// 判断 是Push还是Present进来的
  408. [self.navigationController dismissViewControllerAnimated:NO completion:NULL];
  409. }
  410. - (UIEdgeInsets)contentInset {
  411. return UIEdgeInsetsMake(0, 0, 0, 0);
  412. }
  413. #pragma mark - WKScriptMessageHandler
  414. - (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
  415. /// js call OC function
  416. }
  417. #pragma mark - WKNavigationDelegate
  418. /// 内容开始返回时调用
  419. - (void)webView:(WKWebView *)webView didCommitNavigation:(null_unspecified WKNavigation *)navigation {
  420. UIBarButtonItem *backItem = self.navigationItem.leftBarButtonItems.firstObject;
  421. if (backItem) {
  422. if ([self.webView canGoBack]) {
  423. [self.navigationItem setLeftBarButtonItems:@[backItem, self.closeItem]];
  424. } else {
  425. [self.navigationItem setLeftBarButtonItems:@[backItem]];
  426. }
  427. }
  428. }
  429. - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
  430. if (navigationType==UIWebViewNavigationTypeBackForward) {
  431. self.webView.canGoBack?[self.webView goBack]:[self.navigationController popViewControllerAnimated:YES];
  432. }
  433. return YES;
  434. }
  435. // 导航完成时,会回调(也就是页面载入完成了)
  436. - (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation {
  437. // if (self.viewModel.shouldPullDownToRefresh) [webView.scrollView.mj_header endRefreshing];
  438. // 禁用返回手势
  439. if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
  440. self.navigationController.interactivePopGestureRecognizer.enabled = NO;
  441. }
  442. }
  443. // 导航失败时会回调
  444. - (void)webView:(WKWebView *)webView didFailNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error {
  445. // if (self.viewModel.shouldPullDownToRefresh) [webView.scrollView.mj_header endRefreshing];
  446. // 开启返回手势
  447. if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
  448. self.navigationController.interactivePopGestureRecognizer.enabled = YES;
  449. }
  450. }
  451. // 在发送请求之前,决定是否跳转
  452. - (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
  453. NSLog(@"navigationAction.request.URL: %@", navigationAction.request.URL);
  454. WKNavigationActionPolicy actionPolicy = WKNavigationActionPolicyAllow;//允许
  455. NSString *urlString = [[navigationAction.request URL] absoluteString];
  456. // urlString = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLUserAllowedCharacterSet]];
  457. // urlString = [[urlString mj_url] absoluteString];
  458. // urlString = [urlString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
  459. NSLog(@"跳转:>>>???>>%@",urlString);
  460. // // 拦截WKWebView加载的微信支付统一下单链接, 将redirect_url参数修改为唤起自己App的URLScheme
  461. if ([urlString hasPrefix:@"https://wx.tenpay.com/cgi-bin/mmpayweb-bin/checkmweb"] && ![urlString hasSuffix:[NSString stringWithFormat:@"&redirect_url=https://fj.jppt.com.cn/"]]) {
  462. // decisionHandler(WKNavigationActionPolicyCancel);
  463. // NSString *redirectUrl = nil;
  464. // if ([urlString containsString:@"redirect_url="]) {
  465. // NSRange redirectRange = [urlString rangeOfString:@"redirect_url"];
  466. // redirectUrl = [[urlString substringToIndex:redirectRange.location] stringByAppendingString:[NSString stringWithFormat:@"&redirect_url=https://fj.jppt.com.cn/"]];
  467. // } else {
  468. //// if ([urlString containsString:@"refer_page_name"]) {
  469. //// urlString = [urlString componentsSeparatedByString:@"refer_page_name"].firstObject;
  470. //// }
  471. // redirectUrl = [urlString stringByAppendingString:[NSString stringWithFormat:@"&redirect_url=https://fj.jppt.com.cn/"]];
  472. // }
  473. // NSMutableURLRequest *newRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:redirectUrl] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30];
  474. // newRequest.allHTTPHeaderFields = navigationAction.request.allHTTPHeaderFields;
  475. // newRequest.URL = [NSURL URLWithString:redirectUrl];
  476. // [webView loadRequest:newRequest];
  477. // return;
  478. }
  479. //打开微信
  480. if([urlString containsString:@"weixin://wap/pay?"]) {
  481. actionPolicy =WKNavigationActionPolicyCancel;//不允许跳转
  482. NSURL*url = [NSURL URLWithString:urlString];
  483. if([[UIApplication sharedApplication] respondsToSelector:@selector(openURL:options:completionHandler:)]) {
  484. [[UIApplication sharedApplication] openURL:url options:@{UIApplicationOpenURLOptionUniversalLinksOnly: @NO} completionHandler:^(BOOL success) {
  485. }];
  486. }else{
  487. [[UIApplication sharedApplication]openURL:webView.URL];
  488. }
  489. }
  490. if ([navigationAction.request.URL.host isEqualToString:@"mclient.alipay.com"]) {
  491. // __weak APWebViewController* wself = self;
  492. NSString * urlStr = navigationAction.request.URL.absoluteString;
  493. NSString * returnUrlStr = [urlStr componentsSeparatedByString:@"&return_url="].lastObject;
  494. BOOL isIntercepted = [[AlipaySDK defaultService] payInterceptorWithUrl:urlStr fromScheme:@"JSJPStudent" callback:^(NSDictionary *result) {
  495. // 处理支付结果
  496. NSLog(@"%@", result);
  497. // 返回码,标识支付状态,含义如下:
  498. // 9000——订单支付成功
  499. // 8000——正在处理中
  500. // 4000——订单支付失败
  501. // 5000——重复请求
  502. // 6001——用户中途取消
  503. // 6002——网络连接出错
  504. // isProcessUrlPay 代表 支付宝已经处理该URL
  505. if ([result[@"isProcessUrlPay"] boolValue]) {
  506. // returnUrl 代表 第三方App需要跳转的成功页URL
  507. NSString *urlStr = result[@"returnUrl"];
  508. NSString *resultCode = result[@"resultCode"];
  509. if ([resultCode integerValue] == 9000) {
  510. // TO DO 加载urlStr
  511. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlStr]];
  512. [webView loadRequest:request];
  513. } else if([resultCode integerValue] == 6001){
  514. // TO DO 自己的业务逻辑 urlStr是空的
  515. [webView reload];
  516. }
  517. }
  518. }];
  519. if (isIntercepted) {
  520. decisionHandler(WKNavigationActionPolicyCancel);
  521. return;
  522. } else{
  523. decisionHandler(WKNavigationActionPolicyAllow);
  524. return;
  525. }
  526. }
  527. decisionHandler(actionPolicy);
  528. }
  529. - (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler {
  530. decisionHandler(WKNavigationResponsePolicyAllow);
  531. }
  532. - (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *__nullable credential))completionHandler {
  533. NSURLCredential *cred = [[NSURLCredential alloc] initWithTrust:challenge.protectionSpace.serverTrust];
  534. completionHandler(NSURLSessionAuthChallengeUseCredential, cred);
  535. }
  536. #pragma mark - WKUIDelegate
  537. - (nullable WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures {
  538. /// CoderMike Fixed : 解决点击网页的链接 不跳转的Bug。
  539. WKFrameInfo *frameInfo = navigationAction.targetFrame;
  540. if (![frameInfo isMainFrame]) {
  541. [webView loadRequest:navigationAction.request];
  542. }
  543. return nil;
  544. }
  545. #pragma mark runJavaScript
  546. - (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler {
  547. // [NSObject rq_showAlertViewWithTitle:nil message:message confirmTitle:@"我知道了"];
  548. completionHandler();
  549. }
  550. - (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL result))completionHandler {
  551. completionHandler(YES);
  552. }
  553. - (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(nullable NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * __nullable result))completionHandler {
  554. completionHandler(defaultText);
  555. }
  556. #pragma mark - Getter & Setter
  557. - (UIProgressView *)progressView {
  558. if (!_progressView) {
  559. CGFloat progressViewW = ([[UIScreen mainScreen] bounds].size.width);
  560. CGFloat progressViewH = 3;
  561. CGFloat progressViewX = 0;
  562. CGFloat progressViewY = 0;
  563. UIProgressView *progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(progressViewX, progressViewY, progressViewW, progressViewH)];
  564. progressView.progressTintColor = [UIColor colorWithRed:(253 / 255.0) green:(103 / 255.0) blue:(27 / 255.0) alpha:1];
  565. progressView.trackTintColor = [UIColor clearColor];
  566. [self.view addSubview:progressView];
  567. self.progressView = progressView;
  568. }
  569. return _progressView;
  570. }
  571. - (UIBarButtonItem *)backItem
  572. {
  573. if (_backItem == nil) {
  574. _backItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"backIcon.png"] style:UIBarButtonItemStylePlain target:self action:@selector(_backItemDidClicked)];
  575. self.navigationController.navigationBar.translucent = NO;
  576. [self.navigationItem setLeftBarButtonItem:_backItem];
  577. }
  578. return _backItem;
  579. }
  580. - (UIBarButtonItem *)closeItem {
  581. if (!_closeItem) {
  582. _closeItem = [UIBarButtonItem rq_systemItemWithTitle:@"关闭" titleColor:RQ_MAIN_COLOR imageName:nil target:self selector:@selector(_closeItemDidClicked) textType:YES];
  583. }
  584. return _closeItem;
  585. }
  586. - (void)postuploadPhotoLog {
  587. // if (![Util connectedToNetWork]) {
  588. // showMsgUnconnect();
  589. // return;
  590. // }
  591. NSMutableArray *aArray=[NSMutableArray array];
  592. [aArray addPro:@"idcard" Value:[NSString stringWithFormat:@"%@",RQ_USER_MANAGER.currentUser.loginCode]];
  593. [aArray addPro:@"outid" Value:[NSString stringWithFormat:@"%@",RQ_USER_MANAGER.currentUser.outId]];
  594. NSString* method = @"uploadPhotoLog";
  595. [jiaPeiManager requestAnythingWithURL:method array:aArray data:nil completion:^(NSDictionary *root) {
  596. // if (!root) {
  597. // ShowMsgFailed();
  598. // return ;
  599. // }
  600. //
  601. // if ([root[@"code"] isEqualToString:@"0"]) {
  602. //
  603. // } else {
  604. //// ShowMsg(root[@"msg"]);
  605. // return ;
  606. // }
  607. }];
  608. }
  609. @end