HWWebViewController.m 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927
  1. //
  2. // HWWebViewController.m
  3. //
  4. //
  5. // Created by yhw on 2022/3/9.
  6. //
  7. #import "HWWebViewController.h"
  8. #import <WebKit/WebKit.h>
  9. #import "HWWebViewController.h"
  10. #import "HWToolViewController.h"
  11. #import "HWAddBookmarkViewController.h"
  12. #import "HWBookmarkViewController.h"
  13. #import "HWSetViewController.h"
  14. #import "HWHistoryViewController.h"
  15. #import "HWHistoryModel.h"
  16. #import "iPhone.h"
  17. #import "RSATool.h"
  18. #import "customToastVew.h"
  19. @interface HWWebViewController ()<WKScriptMessageHandler,WKNavigationDelegate,WKUIDelegate,HWToolViewControllerDelete>{
  20. UIView *bgView;/*引导视图*/
  21. }
  22. // 底部工具条
  23. @property (nonatomic,strong) WKWebView *webView;
  24. @property (nonatomic,strong) UIProgressView *progressView;
  25. @property (nonatomic,strong) NSString *shareUrl;
  26. @property (nonatomic,strong) NSString *shareTitle;
  27. @property (nonatomic,strong) NSString *shareImage;
  28. @end
  29. @implementation HWWebViewController
  30. -(void)viewWillAppear:(BOOL)animated
  31. {
  32. [super viewWillAppear:animated];
  33. // addScriptMessageHandler
  34. [self.webView.configuration.userContentController addScriptMessageHandler:self name:@"setShareInfo"];
  35. [self.webView.configuration.userContentController addScriptMessageHandler:self name:@"openShare"];
  36. [self.webView.configuration.userContentController addScriptMessageHandler:self name:@"openApp"];
  37. // 添加KVO监听
  38. [self.webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew
  39. context:nil];
  40. [self.webView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew
  41. context:nil];
  42. [[netWorkManager shareInstance] RefreshThridMsg];
  43. }
  44. - (void)viewDidAppear:(BOOL)animated{
  45. [super viewDidAppear:animated];
  46. [self.webView evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id result, NSError *error) {
  47. if (error == noErr) {
  48. if ([result isKindOfClass:[NSString class]]) {
  49. NSString *userAgent = result;
  50. NSDictionary *infoDic = [[NSBundle mainBundle] infoDictionary];
  51. NSString *appVersion = [infoDic objectForKey:@"CFBundleShortVersionString"];
  52. NSString *newUserAgent = [userAgent stringByAppendingString:[NSString stringWithFormat:@"SZXBrowser/iosVersionNumber/%@/UUID/%@/wkWeb_H/%lf/wkWeb_W/%lf",appVersion,[iPhone phoneDeviceUuid],self.webView.frame.size.height,self.webView.frame.size.width]];
  53. [self.webView setCustomUserAgent:newUserAgent];
  54. }
  55. }
  56. }];
  57. // /*判断是否有安装WhatsApp*/
  58. // if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"whatsapp://"]]){
  59. // NSLog(@"\n---有安装 whatsApp---");
  60. // [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"whatsapp://"]];
  61. // }else{
  62. // NSLog(@"\n+++没有安装 whatsApp+++");
  63. // }
  64. //
  65. // if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"mqq://"]]){
  66. // NSLog(@"\n---有安装 qq---");
  67. // }else{
  68. // NSLog(@"\n+++没有安装 qq+++");
  69. // }
  70. }
  71. - (void)viewWillDisappear:(BOOL)animated
  72. {
  73. [super viewWillDisappear:animated];
  74. // addScriptMessageHandler 很容易导致循环引用 必须手动移除 因此这里要记得移除handlers
  75. [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"setShareInfo"];
  76. [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"openShare"];
  77. [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"openApp"];
  78. // 移除KVO监听
  79. [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
  80. [self.webView removeObserver:self forKeyPath:@"title"];
  81. }
  82. - (void)viewDidLoad {
  83. [super viewDidLoad];
  84. [self drawView];
  85. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateBrowserWindow) name:WebviewReloadNotification object:nil];
  86. if (self.pwd.length > 0){
  87. BOOL haveOpenMask = [HWDataManager getBoolWithKey:Const_Mask_View_Open_Web_Tips];
  88. if (haveOpenMask == NO){
  89. [self addGuideView];
  90. }
  91. }
  92. }
  93. - (void)addGuideView{
  94. bgView = [[UIView alloc] init];
  95. [bgView setBackgroundColor:HW000000Color60];
  96. [self.view addSubview:bgView];
  97. [bgView mas_makeConstraints:^(MASConstraintMaker *make) {
  98. make.left.mas_equalTo(0);
  99. make.bottom.mas_equalTo(0);
  100. make.right.mas_equalTo(0);
  101. make.top.mas_equalTo(0);
  102. }];
  103. UIView *tipsInputView = [[UIView alloc] init];
  104. [tipsInputView setBackgroundColor:[UIColor whiteColor]];
  105. [tipsInputView.layer setCornerRadius:5];
  106. [tipsInputView.layer setBorderWidth:1];
  107. [bgView addSubview:tipsInputView];
  108. [tipsInputView mas_makeConstraints:^(MASConstraintMaker *make) {
  109. make.left.mas_equalTo(10);
  110. make.height.mas_equalTo(36);
  111. make.right.mas_equalTo(-10);
  112. make.top.equalTo(self.navigationBar.textField.mas_top).offset(-1);
  113. }];
  114. /*箭头视图*/
  115. UIImageView *flagImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"guide_open_calcu_flag1"]];
  116. [bgView addSubview:flagImageView];
  117. [flagImageView mas_makeConstraints:^(MASConstraintMaker *make) {
  118. make.right.mas_equalTo(-118.f);
  119. make.height.mas_equalTo(67);
  120. make.width.mas_equalTo(22);
  121. make.top.equalTo(self.navigationBar.mas_bottom);
  122. }];
  123. /*不可点击btn*/
  124. UIButton *unableBtn = [[UIButton alloc] init];
  125. unableBtn.frame = CGRectMake(0, 0, 295, 64);
  126. NSString * curStr = NSLocalizedString(@"guide_set_open_web_guide_tips",nil);
  127. CGFloat curHeight = [curStr boundingRectWithSize:CGSizeMake(295 - 20 , 1000) options:(NSStringDrawingUsesLineFragmentOrigin) attributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:14.f]} context:nil].size.height;
  128. if(curHeight < 50){
  129. curHeight = 50;
  130. }
  131. else{
  132. curHeight += 20;
  133. }
  134. // gradient
  135. CAGradientLayer *gl = [CAGradientLayer layer];
  136. gl.frame = CGRectMake(0,0,295,curHeight);
  137. gl.startPoint = CGPointMake(0, 0.5);
  138. gl.endPoint = CGPointMake(1, 0.5);
  139. gl.colors = @[(__bridge id)HW0CDEFDColor.CGColor, (__bridge id)HW058DFBColor.CGColor];
  140. gl.locations = @[@(0), @(1.0f)];
  141. [unableBtn.layer addSublayer:gl];
  142. [unableBtn setUserInteractionEnabled:NO];
  143. [unableBtn setTitle:curStr forState:(UIControlStateNormal)];
  144. [unableBtn setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
  145. [unableBtn.titleLabel setFont:[UIFont systemFontOfSize:14.f]];
  146. [unableBtn.titleLabel setNumberOfLines:0];
  147. [unableBtn.layer setCornerRadius:curHeight/2.0];
  148. unableBtn.clipsToBounds = YES;
  149. [bgView addSubview:unableBtn];
  150. [unableBtn mas_makeConstraints:^(MASConstraintMaker *make) {
  151. make.right.mas_equalTo(-20*AUTOSCALE);
  152. make.width.mas_equalTo(295);
  153. make.top.equalTo(flagImageView.mas_bottom).offset(-8);
  154. make.height.mas_equalTo(curHeight);
  155. }];
  156. unableBtn.contentEdgeInsets = UIEdgeInsetsMake(0,10, 0, 10);
  157. UIButton *knowBtn = [[UIButton alloc] init];
  158. [knowBtn setBackgroundColor:[UIColor clearColor]];
  159. [knowBtn.layer setCornerRadius:18.f];
  160. [knowBtn.layer setBorderColor:HWFFFFFFColor.CGColor];
  161. [knowBtn.layer setBorderWidth:1];
  162. [knowBtn setTitle:NSLocalizedString(@"guide_set_pwd_guide_know",nil) forState:(UIControlStateNormal)];
  163. [knowBtn setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
  164. [knowBtn.titleLabel setFont:[UIFont systemFontOfSize:16]];
  165. [bgView addSubview:knowBtn];
  166. [knowBtn mas_makeConstraints:^(MASConstraintMaker *make) {
  167. make.right.mas_equalTo(-29*AUTOSCALE);
  168. make.width.mas_equalTo(120);
  169. make.top.equalTo(unableBtn.mas_bottom).offset(15);
  170. make.height.mas_equalTo(36.f);
  171. }];
  172. [knowBtn addTarget:self
  173. action:@selector(knowBtnPressed)
  174. forControlEvents:(UIControlEventTouchUpInside)];
  175. }
  176. - (void)knowBtnPressed{
  177. [bgView removeFromSuperview];
  178. [HWDataManager setBoolWithKey:Const_Mask_View_Open_Web_Tips value:YES];
  179. }
  180. - (void)drawView {
  181. self.view.backgroundColor = [UIColor hwColor:@"#1C1C1E"];
  182. [self.toolBar setHidden:YES];
  183. // WKWebView
  184. WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
  185. self.webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, 0, 0) configuration:config];
  186. // self.webView.backgroundColor = HWBGColor;
  187. self.webView.navigationDelegate = self;
  188. self.webView.UIDelegate = self;
  189. self.webView.backgroundColor = [UIColor hwColor:@"#1C1C1E"];
  190. self.webView.scrollView.backgroundColor = [UIColor hwColor:@"#1C1C1E"];
  191. self.webView.opaque = NO;
  192. self.webView.scrollView.bounces = NO;
  193. self.webView.allowsBackForwardNavigationGestures = YES; //开了支持滑动返回
  194. // self.webView. = NO;
  195. [self.view addSubview:self.webView];
  196. [self.webView mas_makeConstraints:^(MASConstraintMaker *make) {
  197. make.top.mas_equalTo(self.navigationBar.mas_bottom);
  198. make.left.mas_equalTo(0);
  199. make.width.mas_equalTo(SCREEN_W);
  200. make.bottom.mas_equalTo(self.toolBar.mas_top);
  201. }];
  202. //进度条
  203. self.progressView = [[UIProgressView alloc] init];
  204. [self.navigationBar.textField addSubview:self.progressView];
  205. [self.progressView mas_makeConstraints:^(MASConstraintMaker *make) {
  206. make.bottom.mas_equalTo(0);
  207. make.left.mas_equalTo(0);
  208. make.width.mas_equalTo(SCREEN_W);
  209. make.height.mas_offset(2);
  210. }];
  211. // 加载网页
  212. if (self.webUrl.length == 0) { // 百度
  213. [self loadRequestURL:@"https://www.baidu.com/"];
  214. }else if ([self.webUrl containsString:@"https://"] ||
  215. [self.webUrl containsString:@"http://"]) { // 加载网页
  216. [self loadRequestURL:self.webUrl];
  217. }else { // 搜索
  218. NSString *text = [NSString stringWithFormat:@"https://www.baidu.com/s?wd=%@",self.webUrl];
  219. text = [text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
  220. [self loadRequestURL:text];
  221. }
  222. }
  223. - (void)loadRequestURL:(NSString *)urlString {
  224. NSURL *url = [NSURL URLWithString:urlString];
  225. NSURLRequest *request = [NSURLRequest requestWithURL:url];
  226. [self.webView loadRequest:request];
  227. [self.view addSubview:self.webView];
  228. }
  229. #pragma mark - HWSearchBarDelegate
  230. - (void)searchBarWithText:(NSString *)text {
  231. HLog(@"搜索:%@", text)
  232. if(text.length == 4){
  233. [self verifyPwdFun:text];
  234. }
  235. if (text.length != 0) {
  236. if ([text hasPrefix:@"https://"] ||
  237. [text hasPrefix:@"http://"]) {
  238. [self loadRequestURL:text];
  239. }else {
  240. text = [NSString stringWithFormat:@"https://www.baidu.com/s?wd=%@",text];
  241. text = [text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
  242. [self loadRequestURL:text];
  243. }
  244. }
  245. }
  246. - (void)searchBarChangeText:(NSString *)text{
  247. HLog(@"\n----searchBarChangeText===%@-------",text);
  248. if (text.length == 4){
  249. [self verifyPwdFun:text];
  250. }
  251. }
  252. #pragma mark 验证密码是否正确
  253. -(void)verifyPwdFun:(NSString*)text{
  254. /*先判断本地有无设备 无设备时需要先扫码添加设备*/
  255. NSDictionary *deviceDict = [HWDataManager getObjectWithKey:Const_Have_Add_Device];
  256. if (deviceDict && [[deviceDict allKeys] containsObject:Const_Have_Add_Device_SN]){
  257. //有设备了先去做链接准备 // 80bec9c5
  258. NSString *SNStr = deviceDict[@"Const_Have_Add_Device_SN"];
  259. if(SNStr){
  260. NSString *curPwd = nil;
  261. NSString*desPwdStr = nil;
  262. if(ksharedAppDelegate.DeviceThirdIdMod.data.password
  263. && ksharedAppDelegate.DeviceThirdIdMod.data.password.length > 0){
  264. curPwd = ksharedAppDelegate.DeviceThirdIdMod.data.password;
  265. desPwdStr = [RSATool AES128Decrypt:curPwd key:AESCODEKEEYY];
  266. }
  267. else{
  268. if(deviceDict && [[deviceDict allKeys] containsObject:Const_Have_Add_Device_PWD])
  269. {
  270. desPwdStr = deviceDict[Const_Have_Add_Device_PWD];
  271. }
  272. }
  273. if ([desPwdStr isEqualToString:text]){
  274. HLog(@"输入密码正确")
  275. if([AFNetworkReachabilityManager sharedManager].networkReachabilityStatus == AFNetworkReachabilityStatusNotReachable)
  276. {
  277. //[[iToast makeText:NSLocalizedString(@"phone_network_fail_Tips",nil)] show];
  278. customToastVew *view = [customToastVew makeText:NSLocalizedString(@"phone_network_fail_Tips",nil)];
  279. [view show];
  280. [self.view addSubview:view];
  281. return;
  282. }
  283. ksharedAppDelegate.isFirstInputPwdDone = YES;
  284. ksharedAppDelegate.isDidShowPwdType = NO;
  285. [self.view removeFromSuperview];
  286. //被别的设备挤下线 重新链接 如果是链接中 走这个函数会被return
  287. if(![webRtcManager shareManager].isWaitShowLogoutAlert){
  288. [[webRtcManager shareManager] beginToLinkWebRtcFun];
  289. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  290. [[NSNotificationCenter defaultCenter] postNotificationName:didInputPWDNotification object:nil];
  291. });
  292. }
  293. }
  294. else if([text isEqualToString:keyToForgetPwd]){
  295. [[NSNotificationCenter defaultCenter] postNotificationName:forgetPwdNotification object:nil];
  296. }
  297. }
  298. }
  299. }
  300. #pragma mark - HWToolBarDelegate
  301. - (void)backBtnDidClick {
  302. HLog(@"后退");
  303. if ([self.webView canGoBack]) {
  304. [self.webView goBack];
  305. }else {
  306. [self.navigationController popViewControllerAnimated:YES];
  307. }
  308. // 更新缓存
  309. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  310. [self updateBrowserWindow];
  311. });
  312. }
  313. - (void)forwardBtnDidClick {
  314. HLog(@"前进");
  315. if ([self.webView canGoForward]) {
  316. [self.webView goForward];
  317. }
  318. // 更新缓存
  319. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  320. [self updateBrowserWindow];
  321. });
  322. }
  323. #pragma mark- 监听加载进度
  324. - (void)observeValueForKeyPath:(NSString *)keyPath
  325. ofObject:(id)object
  326. change:(NSDictionary<NSString *,id> *)change
  327. context:(void *)context
  328. {
  329. HLog(@"加载进度:%.2f", self.webView.estimatedProgress);
  330. NSArray *arrViewControllers = self.navigationController.viewControllers;
  331. NSInteger index = [arrViewControllers indexOfObject:self];
  332. self.toolBar.backBtn.enabled = [self.webView canGoBack] || index > 0;
  333. self.toolBar.forwardBtn.enabled = [self.webView canGoForward];
  334. if ([keyPath isEqualToString:@"estimatedProgress"]) {
  335. self.progressView.progress = self.webView.estimatedProgress;
  336. // 加载完成
  337. if (self.webView.estimatedProgress >= 1.0f ) {
  338. [UIView animateWithDuration:0.25f animations:^{
  339. self.progressView.alpha = 0.0f;
  340. self.progressView.progress = 0.0f;
  341. }];
  342. }else{
  343. self.progressView.alpha = 1.0f;
  344. // 记录历史
  345. [self saveHistory];
  346. // 更新缓存
  347. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  348. [self updateBrowserWindow];
  349. });
  350. }
  351. }else if ([keyPath isEqualToString:@"title"]) {
  352. if (object == self.webView) {
  353. // [self.navigationBar.textField setText:self.webView.title];
  354. self.navigationBar.searchImageView.hidden = self.webView.title.length != 0;
  355. self.navigationBar.searchPlaceHolder.hidden = self.webView.title.length != 0;
  356. } else {
  357. [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
  358. }
  359. }
  360. }
  361. #pragma mark 事件代理
  362. // 页面开始加载时调用
  363. -(void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{
  364. self.shareTitle = @"";
  365. self.shareUrl = @"";
  366. self.shareImage = @"";
  367. [self showWebView0];
  368. }
  369. // 当内容开始返回时调用
  370. - (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation{
  371. }
  372. // 页面加载完成之后调用
  373. - (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{//这里修改导航栏的标题,动态改变
  374. HLog(@"webViewtitle:%@",webView.title);
  375. // [self.webView evaluateJavaScript:@"document.getElementsByTagName('body')[0].style.background='#2D2F35'" completionHandler:nil];
  376. //
  377. //// if (webView.title && webView.title.length > 0 ) {
  378. //// [self.navigationBar.textField setText:webView.title];
  379. //// }
  380. [self removeNewIndicator];
  381. // 更新缓存
  382. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  383. [self updateBrowserWindow];
  384. });
  385. [self showWebView1];
  386. }
  387. // 页面加载失败时调用
  388. - (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation{
  389. [self removeNewIndicator];
  390. // [self.webView evaluateJavaScript:@"document.getElementsByTagName('body')[0].style.background='#2D2F35'" completionHandler:nil];
  391. // 更新缓存
  392. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  393. [self updateBrowserWindow];
  394. });
  395. [self showWebView3];
  396. }
  397. #pragma mark - 解决wkwebView闪白问题
  398. // 解决wkwebView闪白问题
  399. - (void)showWebView0 {
  400. self.webView.hidden = YES;
  401. [self performSelector:@selector(showWebView1) withObject:self afterDelay:1];
  402. [self showNewIndicatorWithCanBack:YES canTouch:NO];
  403. }
  404. // 1改变网页内容背景颜色
  405. - (void)showWebView1 {
  406. [self performSelector:@selector(showWebView2) withObject:self afterDelay:0.2];
  407. }
  408. // 2加载成功
  409. - (void)showWebView2 {
  410. [self removeNewIndicator];
  411. self.webView.hidden = NO;
  412. }
  413. // 3加载失败
  414. - (void)showWebView3 {
  415. [self removeNewIndicator];
  416. }
  417. // 接收到服务器跳转请求之后再执行
  418. - (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation{
  419. }
  420. // 在收到响应后,决定是否跳转
  421. - (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler{
  422. // HLog(@"%@",webView);
  423. // HLog(@"%@",navigationResponse);
  424. WKNavigationResponsePolicy actionPolicy = WKNavigationResponsePolicyAllow;
  425. //这句是必须加上的,不然会异常
  426. decisionHandler(actionPolicy);
  427. NSArray *arrViewControllers = self.navigationController.viewControllers;
  428. NSInteger index = [arrViewControllers indexOfObject:self];
  429. self.toolBar.backBtn.enabled = [self.webView canGoBack] || index > 0;
  430. self.toolBar.forwardBtn.enabled = [self.webView canGoForward];
  431. // if (webView.title && webView.title.length > 0 ) {
  432. // [self.navigationBar.textField setText:webView.title];
  433. // }
  434. }
  435. // 在发送请求之前,决定是否跳转
  436. - (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
  437. HLog(@"URL=======%@", navigationAction.request.URL);
  438. HLog(@"URL.scheme=======%@", navigationAction.request.URL.scheme);
  439. if (navigationAction.targetFrame == nil) {
  440. [webView loadRequest:navigationAction.request];
  441. }
  442. if (navigationAction.navigationType==WKNavigationTypeBackForward) {//判断是返回类型
  443. }
  444. //这句是必须加上的,不然会异常
  445. decisionHandler(WKNavigationActionPolicyAllow);
  446. NSString *url = navigationAction.request.URL.absoluteString;
  447. HLog(@"支付url:%@", url);
  448. if ([url containsString:@"weixin:"]) {
  449. [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url] options:@{} completionHandler:^(BOOL success) {
  450. if (!success) { // 打开微信失败
  451. [self toShowNoWX];
  452. }
  453. }];
  454. }else if ([url containsString:@"alipay:"]) {
  455. [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url] options:@{} completionHandler:^(BOOL success) {
  456. if (!success) { // 打开支付宝失败
  457. [self toShowNoZFB];
  458. }
  459. }];
  460. }else if ([url containsString:@"https://jq.qq.com/"]) { // 加入QQ群
  461. [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url] options:@{} completionHandler:^(BOOL success) {
  462. }];
  463. }
  464. }
  465. - (void)toShowNoWX {
  466. NSString *tipsStr = @"您的手机未安装微信,请先安装后再进行支付或者选择其他支付方式";
  467. UIAlertAction *sureAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"other_confirm",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
  468. }];
  469. [sureAction setValue:[UIColor hwColor:@"#FFFFFF"] forKey:@"titleTextColor"];//iOS8.3
  470. UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:tipsStr message:@"" preferredStyle:(UIAlertControllerStyleAlert)];
  471. alertVC.overrideUserInterfaceStyle = UIUserInterfaceStyleDark;
  472. [alertVC addAction:sureAction];
  473. [self presentViewController:alertVC animated:YES completion:^{
  474. }];
  475. }
  476. - (void)toShowNoZFB {
  477. NSString *tipsStr = NSLocalizedString(@"no_air_pay_tips",nil);
  478. UIAlertAction *sureAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"other_confirm",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
  479. }];
  480. [sureAction setValue:[UIColor hwColor:@"#FFFFFF"] forKey:@"titleTextColor"];//iOS8.3
  481. UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:tipsStr message:@"" preferredStyle:(UIAlertControllerStyleAlert)];
  482. alertVC.overrideUserInterfaceStyle = UIUserInterfaceStyleDark;
  483. [alertVC addAction:sureAction];
  484. [self presentViewController:alertVC animated:YES completion:^{
  485. }];
  486. }
  487. #pragma mark - WKScriptMessageHandler
  488. - (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
  489. // HLog(@"%@",NSStringFromSelector(_cmd));
  490. // HLog(@"%@",message);
  491. HLog(@"%@",message.body);
  492. HLog(@"%@",message.name);
  493. //这个是注入JS代码后的处理效果,尽管html已经有实现了,但是没用,还是执行JS中的实现
  494. if ([message.name isEqualToString:@"setShareInfo"]) {
  495. HLog(@"%@",message.body);
  496. HLog(@"%@",message.name);
  497. NSDictionary *bodyDict = message.body;
  498. if ([[bodyDict allKeys] containsObject:@"title"]) {
  499. self.shareTitle = [bodyDict objectForKey:@"title"];
  500. }
  501. if ([[bodyDict allKeys] containsObject:@"gotoUrl"]) {
  502. self.shareUrl = [bodyDict objectForKey:@"gotoUrl"];
  503. }
  504. if ([[bodyDict allKeys] containsObject:@"shareImg"]) {
  505. self.shareImage = [bodyDict objectForKey:@"shareImg"];
  506. }
  507. }else if ([message.name isEqualToString:@"openShare"]) {
  508. NSDictionary *bodyDict = message.body;
  509. if ([[bodyDict allKeys] containsObject:@"title"]) {
  510. self.shareTitle = [bodyDict objectForKey:@"title"];
  511. }
  512. if ([[bodyDict allKeys] containsObject:@"gotoUrl"]) {
  513. self.shareUrl = [bodyDict objectForKey:@"gotoUrl"];
  514. }
  515. if ([[bodyDict allKeys] containsObject:@"shareImg"]) {
  516. self.shareImage = [bodyDict objectForKey:@"shareImg"];
  517. }
  518. // 分享
  519. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  520. [self share];
  521. });
  522. }else if ([message.name isEqualToString:@"openApp"]) {
  523. NSString *openUrl = [NSString stringWithFormat:@"%@",message.body];
  524. if ([openUrl containsString:@"whatsapp"]){
  525. /*判断是否有安装WhatsApp*/
  526. if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"whatsapp://"]]){
  527. NSLog(@"\n---有安装 whatsApp---");
  528. [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"whatsapp://"]];
  529. }else{
  530. [[iToast makeText:NSLocalizedString(@"app_install_whatsApp_tips",nil)] show];
  531. }
  532. return;
  533. }
  534. [[UIApplication sharedApplication] openURL:[NSURL URLWithString:openUrl] options:@{} completionHandler:^(BOOL success) {
  535. }];
  536. }else {
  537. HLog(@"其他类型");
  538. }
  539. }
  540. - (void)toolBtnDidClick {
  541. HLog(@"工具");
  542. HWToolViewController *vc = [[HWToolViewController alloc] init];
  543. vc.modalPresentationStyle = UIModalPresentationCustom;
  544. vc.delegate = self;
  545. vc.isSetUnavailable = NO;
  546. [self presentViewController:vc animated:YES completion:^{
  547. vc.view.superview.backgroundColor = RGBACOLOR(0, 0, 0, 0.25);
  548. }];
  549. }
  550. #pragma mark HWToolViewControllerDelete
  551. - (void)toolDidClickItem:(NSString *)title {
  552. if ([title isEqualToString:NSLocalizedString(@"more_add_bookmark",nil)]) {
  553. HLog(@"添加书签");
  554. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  555. HWAddBookmarkViewController *vc = [[HWAddBookmarkViewController alloc] init];
  556. // BaseModel *model = [[BaseModel alloc] init];
  557. NSInteger ID = [HWDataManager getIntegerWithKey:BrowserWindowsCurrentID];
  558. NSString *IDValue = [NSString stringWithFormat:@"%ld", ID];
  559. NSString *where = [NSString stringWithFormat:@"where %@=%@",bg_sqlKey(@"ID"),bg_sqlValue(IDValue)];
  560. NSArray *modelArr = [BaseModel bg_find:DB_BrowserWindows_TableName where:where];
  561. BaseModel *model = modelArr.firstObject;
  562. vc.model = model;
  563. [self presentViewController:vc animated:YES completion:^{
  564. }];
  565. });
  566. }else if ([title isEqualToString:NSLocalizedString(@"more_bookmark",nil)]) {
  567. HLog(@"书签");
  568. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  569. HWBookmarkViewController *vc = [[HWBookmarkViewController alloc] init];
  570. [self.navigationController pushViewController:vc animated:YES];
  571. });
  572. }else if ([title isEqualToString:NSLocalizedString(@"more_history",nil)]) {
  573. HLog(@"历史");
  574. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  575. HWHistoryViewController *vc = [[HWHistoryViewController alloc] init];
  576. [self.navigationController pushViewController:vc animated:YES];
  577. });
  578. }else if ([title isEqualToString:NSLocalizedString(@"more_set",nil)]) {
  579. HLog(@"设置");
  580. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  581. HWSetViewController *vc = [[HWSetViewController alloc] init];
  582. [self.navigationController pushViewController:vc animated:YES];
  583. });
  584. }else if ([title isEqualToString:NSLocalizedString(@"more_traceless",nil)]) {
  585. HLog(@"无痕");
  586. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  587. BOOL isNoTrackModel = [HWDataManager getBoolWithKey:Const_IsNoTrackModel];
  588. if (isNoTrackModel) {
  589. [[iToast makeText:NSLocalizedString(@"other_close_traceless",nil)] show];
  590. [HWDataManager setBoolWithKey:Const_IsNoTrackModel value:NO];
  591. }else {
  592. [[iToast makeText:NSLocalizedString(@"other_open_traceless",nil)] show];
  593. [HWDataManager setBoolWithKey:Const_IsNoTrackModel value:YES];
  594. }
  595. });
  596. }else if ([title isEqualToString:NSLocalizedString(@"more_refresh",nil)]) {
  597. HLog(@"刷新");
  598. [self.webView reload];
  599. }else if ([title isEqualToString:NSLocalizedString(@"more_share",nil)]) {
  600. HLog(@"分享");
  601. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  602. [self share];
  603. });
  604. }
  605. }
  606. - (void)share {
  607. //分享的标题
  608. NSString *textToShare = self.webView.title;
  609. if (self.shareTitle.length != 0) {
  610. textToShare = self.shareTitle;
  611. }
  612. //分享的图片
  613. UIImage *imageToShare = [UIImage imageNamed:@"logo_pic"];
  614. //分享的url
  615. NSURL *urlToShare = self.webView.URL;
  616. if (self.shareUrl.length != 0) {
  617. urlToShare = [NSURL URLWithString:self.shareUrl];
  618. }
  619. NSArray *activityItems = @[textToShare,imageToShare, urlToShare];
  620. UIActivityViewController *activityVC = [[UIActivityViewController alloc] initWithActivityItems:activityItems applicationActivities:nil];
  621. activityVC.excludedActivityTypes = @[UIActivityTypePrint,UIActivityTypePostToWeibo, UIActivityTypeCopyToPasteboard,UIActivityTypeAssignToContact,UIActivityTypeSaveToCameraRoll];
  622. [self presentViewController:activityVC animated:YES completion:nil];
  623. //分享之后的回调
  624. activityVC.completionWithItemsHandler = ^(UIActivityType _Nullable activityType, BOOL completed, NSArray * _Nullable returnedItems, NSError * _Nullable activityError) {
  625. if (completed) {
  626. HLog(@"分享 成功");
  627. } else {
  628. HLog(@"分享 取消");
  629. }
  630. };
  631. }
  632. #pragma mark 截图
  633. - (void)updateBrowserWindow {
  634. // 浏览器当前窗口索引ID
  635. NSInteger ID = [HWDataManager getIntegerWithKey:BrowserWindowsCurrentID];
  636. NSString *IDValue = [NSString stringWithFormat:@"%ld", ID];
  637. NSString *where = [NSString stringWithFormat:@"where %@=%@",bg_sqlKey(@"ID"),bg_sqlValue(IDValue)];
  638. NSArray *modelArr = [BaseModel bg_find:DB_BrowserWindows_TableName where:where];
  639. NSArray *dataArray = [BaseModel bg_findAll:DB_BrowserWindows_TableName];
  640. if (dataArray.count == 0) { // 无窗口
  641. BaseModel *model = [[BaseModel alloc] init];
  642. model.ID = 0;
  643. model.name = @"主页";
  644. // 更新URL
  645. model.webUrl = Const_HomeUrl;
  646. // 更新截图
  647. // UIImage *image = [self getScreenShotImage];
  648. // if (image) {
  649. // NSString *imageName = [NSString stringWithFormat:@"%ld", ID];
  650. // NSString *imageUrl = [HWDataManager writeScreenShotImageToLocal:image withName:imageName];
  651. // model.iconFile = imageUrl;
  652. // }
  653. // 更新数据库
  654. model.bg_tableName = DB_BrowserWindows_TableName;
  655. [model bg_saveOrUpdateAsync:^(BOOL isSuccess) {
  656. HLog(@"BaseModel更新: %@", isSuccess ? @"成功":@"失败");
  657. }];
  658. [HWDataManager setIntegerWithKey:BrowserWindowsCurrentID value:0];
  659. [self loadRequestURL:model.webUrl];
  660. }else if (modelArr.count == 0) { // 当前窗口已被删除 更新BrowserWindowsCurrentID
  661. BaseModel *lastModel = [BaseModel bg_lastObject:DB_BrowserWindows_TableName];
  662. [HWDataManager setIntegerWithKey:BrowserWindowsCurrentID value:lastModel.ID];
  663. [self loadRequestURL:lastModel.webUrl];
  664. }else { // 当前窗口加载页面 更新model
  665. BaseModel *model = modelArr.firstObject;
  666. model.ID = ID;
  667. model.name = self.webView.title;
  668. // 更新URL
  669. model.webUrl = self.webView.URL.absoluteString;
  670. // 更新截图
  671. // UIImage *image = [self getScreenShotImage];
  672. // if (image) {
  673. // NSString *imageName = [NSString stringWithFormat:@"%ld", ID];
  674. // NSString *imageUrl = [HWDataManager writeScreenShotImageToLocal:image withName:imageName];
  675. // model.iconFile = imageUrl;
  676. // }
  677. // 更新数据库
  678. model.bg_tableName = DB_BrowserWindows_TableName;
  679. [model bg_saveOrUpdateAsync:^(BOOL isSuccess) {
  680. HLog(@"BaseModel更新: %@", isSuccess ? @"成功":@"失败");
  681. }];
  682. }
  683. }
  684. /**WKWebView截图*/
  685. - (UIImage *)getScreenShotImage {
  686. UIScrollView *scrollView = self.webView.scrollView;
  687. // 1. 记录当前 scrollView 的偏移和位置
  688. CGPoint currentOffset = scrollView.contentOffset;
  689. CGRect currentFrame = scrollView.frame;
  690. scrollView.contentOffset = CGPointZero;
  691. // 2. 将 scrollView 展开为其实际内容的大小
  692. scrollView.frame = CGRectMake(0, 0, self.webView.frame.size.width, self.webView.frame.size.height);
  693. // 3. 第三个参数设置为 0 表示设置为屏幕的默认缩放因子
  694. UIGraphicsBeginImageContextWithOptions(scrollView.frame.size, YES, 0);
  695. [scrollView.layer renderInContext:UIGraphicsGetCurrentContext()];
  696. UIImage *snapshotImage = UIGraphicsGetImageFromCurrentImageContext();
  697. UIGraphicsEndImageContext();
  698. // 4. 重新设置 scrollView 的偏移和位置,还原现场
  699. scrollView.contentOffset = currentOffset;
  700. scrollView.frame = currentFrame;
  701. return snapshotImage;
  702. }
  703. #pragma mark 历史记录
  704. - (void)saveHistory {
  705. BOOL isNoTrackModel = [HWDataManager getBoolWithKey:Const_IsNoTrackModel];
  706. if (isNoTrackModel) {
  707. return;
  708. }
  709. HWHistoryModel *model = [[HWHistoryModel alloc] init];
  710. model.name = self.webView.title;
  711. model.webUrl = self.webView.URL.absoluteString;
  712. model.cTime = [iTools getNowTimeStamp];
  713. // 更新数据库
  714. model.bg_tableName = DB_Bookmark_History_TableName;
  715. [model bg_saveOrUpdateAsync:^(BOOL isSuccess) {
  716. HLog(@"HWHistoryModel 更新: %@", isSuccess ? @"成功":@"失败");
  717. }];
  718. }
  719. - (void)dealloc {
  720. [[NSNotificationCenter defaultCenter] removeObserver:self];
  721. }
  722. @end