RQWebViewViewController.m 31 KB

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