HWWebViewController.m 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925
  1. //
  2. // HWWebViewController.m
  3. // 双子星云手机
  4. //
  5. // Created by 余衡武 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 "connectDeviceManager.h"
  18. #import "RSATool.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. [[connectDeviceManager 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 ([_pwd isEqualToString:text] && (_pwd.length == 4)){
  236. // [connectDeviceManager shareInstance].isFirstInputPwdDone = YES;
  237. //
  238. // [self.view removeFromSuperview];
  239. // [[NSNotificationCenter defaultCenter] postNotificationName:ShowImgAndVoiceNotification object:nil];
  240. // }
  241. if (text.length != 0) {
  242. if ([text hasPrefix:@"https://"] ||
  243. [text hasPrefix:@"http://"]) {
  244. [self loadRequestURL:text];
  245. }else {
  246. text = [NSString stringWithFormat:@"https://www.baidu.com/s?wd=%@",text];
  247. text = [text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
  248. [self loadRequestURL:text];
  249. }
  250. }
  251. }
  252. - (void)searchBarChangeText:(NSString *)text{
  253. HLog(@"\n----searchBarChangeText===%@-------",text);
  254. if (text.length == 4){
  255. [self verifyPwdFun:text];
  256. }
  257. }
  258. #pragma mark 验证密码是否正确
  259. -(void)verifyPwdFun:(NSString*)text{
  260. /*先判断本地有无设备 无设备时需要先扫码添加设备*/
  261. NSDictionary *deviceDict = [HWDataManager getObjectWithKey:Const_Have_Add_Device];
  262. if (deviceDict && [[deviceDict allKeys] containsObject:Const_Have_Add_Device_SN]){
  263. //有设备了先去做链接准备 // 80bec9c5
  264. NSString *SNStr = deviceDict[@"Const_Have_Add_Device_SN"];
  265. if(SNStr){
  266. // [[connectDeviceManager shareInstance] getThridMsgBySN:SNStr needReconnect:NO didNetEnd:^(bool didSuc) {
  267. //
  268. // if(didSuc){
  269. NSString *curPwd = nil;
  270. NSString*desPwdStr = nil;
  271. if([connectDeviceManager shareInstance].DeviceThirdIdMod.data.password
  272. && [connectDeviceManager shareInstance].DeviceThirdIdMod.data.password.length > 0){
  273. curPwd = [connectDeviceManager shareInstance].DeviceThirdIdMod.data.password;
  274. desPwdStr = [RSATool AES128Decrypt:curPwd key:AESCODEKEEYY];
  275. }
  276. else{
  277. if(deviceDict && [[deviceDict allKeys] containsObject:Const_Have_Add_Device_PWD])
  278. {
  279. desPwdStr = deviceDict[Const_Have_Add_Device_PWD];
  280. }
  281. }
  282. if ([desPwdStr isEqualToString:text]){
  283. [connectDeviceManager shareInstance].isFirstInputPwdDone = YES;
  284. [self.view removeFromSuperview];
  285. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  286. [[NSNotificationCenter defaultCenter] postNotificationName:ShowImgAndVoiceNotification object:nil];
  287. });
  288. }
  289. else if([text isEqualToString:keyToForgetPwd]){
  290. [[NSNotificationCenter defaultCenter] postNotificationName:forgetPwdNotification object:nil];
  291. }
  292. // }
  293. // else{
  294. //
  295. // }
  296. //
  297. // }];
  298. }
  299. }
  300. }
  301. #pragma mark - HWToolBarDelegate
  302. - (void)backBtnDidClick {
  303. HLog(@"后退");
  304. if ([self.webView canGoBack]) {
  305. [self.webView goBack];
  306. }else {
  307. [self.navigationController popViewControllerAnimated:YES];
  308. }
  309. // 更新缓存
  310. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  311. [self updateBrowserWindow];
  312. });
  313. }
  314. - (void)forwardBtnDidClick {
  315. HLog(@"前进");
  316. if ([self.webView canGoForward]) {
  317. [self.webView goForward];
  318. }
  319. // 更新缓存
  320. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  321. [self updateBrowserWindow];
  322. });
  323. }
  324. #pragma mark- 监听加载进度
  325. - (void)observeValueForKeyPath:(NSString *)keyPath
  326. ofObject:(id)object
  327. change:(NSDictionary<NSString *,id> *)change
  328. context:(void *)context
  329. {
  330. HLog(@"加载进度:%.2f", self.webView.estimatedProgress);
  331. NSArray *arrViewControllers = self.navigationController.viewControllers;
  332. NSInteger index = [arrViewControllers indexOfObject:self];
  333. self.toolBar.backBtn.enabled = [self.webView canGoBack] || index > 0;
  334. self.toolBar.forwardBtn.enabled = [self.webView canGoForward];
  335. if ([keyPath isEqualToString:@"estimatedProgress"]) {
  336. self.progressView.progress = self.webView.estimatedProgress;
  337. // 加载完成
  338. if (self.webView.estimatedProgress >= 1.0f ) {
  339. [UIView animateWithDuration:0.25f animations:^{
  340. self.progressView.alpha = 0.0f;
  341. self.progressView.progress = 0.0f;
  342. }];
  343. }else{
  344. self.progressView.alpha = 1.0f;
  345. // 记录历史
  346. [self saveHistory];
  347. // 更新缓存
  348. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  349. [self updateBrowserWindow];
  350. });
  351. }
  352. }else if ([keyPath isEqualToString:@"title"]) {
  353. if (object == self.webView) {
  354. // [self.navigationBar.textField setText:self.webView.title];
  355. self.navigationBar.searchImageView.hidden = self.webView.title.length != 0;
  356. self.navigationBar.searchPlaceHolder.hidden = self.webView.title.length != 0;
  357. } else {
  358. [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
  359. }
  360. }
  361. }
  362. #pragma mark 事件代理
  363. // 页面开始加载时调用
  364. -(void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{
  365. self.shareTitle = @"";
  366. self.shareUrl = @"";
  367. self.shareImage = @"";
  368. [self showWebView0];
  369. }
  370. // 当内容开始返回时调用
  371. - (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation{
  372. }
  373. // 页面加载完成之后调用
  374. - (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{//这里修改导航栏的标题,动态改变
  375. HLog(@"webViewtitle:%@",webView.title);
  376. // [self.webView evaluateJavaScript:@"document.getElementsByTagName('body')[0].style.background='#2D2F35'" completionHandler:nil];
  377. //
  378. //// if (webView.title && webView.title.length > 0 ) {
  379. //// [self.navigationBar.textField setText:webView.title];
  380. //// }
  381. [self removeNewIndicator];
  382. // 更新缓存
  383. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  384. [self updateBrowserWindow];
  385. });
  386. [self showWebView1];
  387. }
  388. // 页面加载失败时调用
  389. - (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation{
  390. [self removeNewIndicator];
  391. // [self.webView evaluateJavaScript:@"document.getElementsByTagName('body')[0].style.background='#2D2F35'" completionHandler:nil];
  392. // 更新缓存
  393. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  394. [self updateBrowserWindow];
  395. });
  396. [self showWebView3];
  397. }
  398. #pragma mark - 解决wkwebView闪白问题
  399. // 解决wkwebView闪白问题
  400. - (void)showWebView0 {
  401. self.webView.hidden = YES;
  402. [self performSelector:@selector(showWebView1) withObject:self afterDelay:1];
  403. [self showNewIndicatorWithCanBack:YES canTouch:NO];
  404. }
  405. // 1改变网页内容背景颜色
  406. - (void)showWebView1 {
  407. [self performSelector:@selector(showWebView2) withObject:self afterDelay:0.2];
  408. }
  409. // 2加载成功
  410. - (void)showWebView2 {
  411. [self removeNewIndicator];
  412. self.webView.hidden = NO;
  413. }
  414. // 3加载失败
  415. - (void)showWebView3 {
  416. [self removeNewIndicator];
  417. }
  418. // 接收到服务器跳转请求之后再执行
  419. - (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation{
  420. }
  421. // 在收到响应后,决定是否跳转
  422. - (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler{
  423. // HLog(@"%@",webView);
  424. // HLog(@"%@",navigationResponse);
  425. WKNavigationResponsePolicy actionPolicy = WKNavigationResponsePolicyAllow;
  426. //这句是必须加上的,不然会异常
  427. decisionHandler(actionPolicy);
  428. NSArray *arrViewControllers = self.navigationController.viewControllers;
  429. NSInteger index = [arrViewControllers indexOfObject:self];
  430. self.toolBar.backBtn.enabled = [self.webView canGoBack] || index > 0;
  431. self.toolBar.forwardBtn.enabled = [self.webView canGoForward];
  432. // if (webView.title && webView.title.length > 0 ) {
  433. // [self.navigationBar.textField setText:webView.title];
  434. // }
  435. }
  436. // 在发送请求之前,决定是否跳转
  437. - (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
  438. HLog(@"URL=======%@", navigationAction.request.URL);
  439. HLog(@"URL.scheme=======%@", navigationAction.request.URL.scheme);
  440. if (navigationAction.targetFrame == nil) {
  441. [webView loadRequest:navigationAction.request];
  442. }
  443. if (navigationAction.navigationType==WKNavigationTypeBackForward) {//判断是返回类型
  444. }
  445. //这句是必须加上的,不然会异常
  446. decisionHandler(WKNavigationActionPolicyAllow);
  447. NSString *url = navigationAction.request.URL.absoluteString;
  448. HLog(@"支付url:%@", url);
  449. if ([url containsString:@"weixin:"]) {
  450. [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url] options:@{} completionHandler:^(BOOL success) {
  451. if (!success) { // 打开微信失败
  452. [self toShowNoWX];
  453. }
  454. }];
  455. }else if ([url containsString:@"alipay:"]) {
  456. [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url] options:@{} completionHandler:^(BOOL success) {
  457. if (!success) { // 打开支付宝失败
  458. [self toShowNoZFB];
  459. }
  460. }];
  461. }else if ([url containsString:@"https://jq.qq.com/"]) { // 加入QQ群
  462. [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url] options:@{} completionHandler:^(BOOL success) {
  463. }];
  464. }
  465. }
  466. - (void)toShowNoWX {
  467. NSString *tipsStr = @"您的手机未安装微信,请先安装后再进行支付或者选择其他支付方式";
  468. UIAlertAction *sureAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"other_confirm",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
  469. }];
  470. [sureAction setValue:[UIColor hwColor:@"#FFFFFF"] forKey:@"titleTextColor"];//iOS8.3
  471. UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:tipsStr message:@"" preferredStyle:(UIAlertControllerStyleAlert)];
  472. alertVC.overrideUserInterfaceStyle = UIUserInterfaceStyleDark;
  473. [alertVC addAction:sureAction];
  474. [self presentViewController:alertVC animated:YES completion:^{
  475. }];
  476. }
  477. - (void)toShowNoZFB {
  478. NSString *tipsStr = NSLocalizedString(@"no_air_pay_tips",nil);
  479. UIAlertAction *sureAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"other_confirm",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
  480. }];
  481. [sureAction setValue:[UIColor hwColor:@"#FFFFFF"] forKey:@"titleTextColor"];//iOS8.3
  482. UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:tipsStr message:@"" preferredStyle:(UIAlertControllerStyleAlert)];
  483. alertVC.overrideUserInterfaceStyle = UIUserInterfaceStyleDark;
  484. [alertVC addAction:sureAction];
  485. [self presentViewController:alertVC animated:YES completion:^{
  486. }];
  487. }
  488. #pragma mark - WKScriptMessageHandler
  489. - (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
  490. // HLog(@"%@",NSStringFromSelector(_cmd));
  491. // HLog(@"%@",message);
  492. HLog(@"%@",message.body);
  493. HLog(@"%@",message.name);
  494. //这个是注入JS代码后的处理效果,尽管html已经有实现了,但是没用,还是执行JS中的实现
  495. if ([message.name isEqualToString:@"setShareInfo"]) {
  496. HLog(@"%@",message.body);
  497. HLog(@"%@",message.name);
  498. NSDictionary *bodyDict = message.body;
  499. if ([[bodyDict allKeys] containsObject:@"title"]) {
  500. self.shareTitle = [bodyDict objectForKey:@"title"];
  501. }
  502. if ([[bodyDict allKeys] containsObject:@"gotoUrl"]) {
  503. self.shareUrl = [bodyDict objectForKey:@"gotoUrl"];
  504. }
  505. if ([[bodyDict allKeys] containsObject:@"shareImg"]) {
  506. self.shareImage = [bodyDict objectForKey:@"shareImg"];
  507. }
  508. }else if ([message.name isEqualToString:@"openShare"]) {
  509. NSDictionary *bodyDict = message.body;
  510. if ([[bodyDict allKeys] containsObject:@"title"]) {
  511. self.shareTitle = [bodyDict objectForKey:@"title"];
  512. }
  513. if ([[bodyDict allKeys] containsObject:@"gotoUrl"]) {
  514. self.shareUrl = [bodyDict objectForKey:@"gotoUrl"];
  515. }
  516. if ([[bodyDict allKeys] containsObject:@"shareImg"]) {
  517. self.shareImage = [bodyDict objectForKey:@"shareImg"];
  518. }
  519. // 分享
  520. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  521. [self share];
  522. });
  523. }else if ([message.name isEqualToString:@"openApp"]) {
  524. NSString *openUrl = [NSString stringWithFormat:@"%@",message.body];
  525. if ([openUrl containsString:@"whatsapp"]){
  526. /*判断是否有安装WhatsApp*/
  527. if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"whatsapp://"]]){
  528. NSLog(@"\n---有安装 whatsApp---");
  529. [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"whatsapp://"]];
  530. }else{
  531. [[iToast makeText:NSLocalizedString(@"app_install_whatsApp_tips",nil)] show];
  532. }
  533. return;
  534. }
  535. [[UIApplication sharedApplication] openURL:[NSURL URLWithString:openUrl] options:@{} completionHandler:^(BOOL success) {
  536. }];
  537. }else {
  538. HLog(@"其他类型");
  539. }
  540. }
  541. - (void)toolBtnDidClick {
  542. HLog(@"工具");
  543. HWToolViewController *vc = [[HWToolViewController alloc] init];
  544. vc.modalPresentationStyle = UIModalPresentationCustom;
  545. vc.delegate = self;
  546. vc.isSetUnavailable = NO;
  547. [self presentViewController:vc animated:YES completion:^{
  548. vc.view.superview.backgroundColor = RGBACOLOR(0, 0, 0, 0.25);
  549. }];
  550. }
  551. #pragma mark HWToolViewControllerDelete
  552. - (void)toolDidClickItem:(NSString *)title {
  553. if ([title isEqualToString:NSLocalizedString(@"more_add_bookmark",nil)]) {
  554. HLog(@"添加书签");
  555. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  556. HWAddBookmarkViewController *vc = [[HWAddBookmarkViewController alloc] init];
  557. // BaseModel *model = [[BaseModel alloc] init];
  558. NSInteger ID = [HWDataManager getIntegerWithKey:BrowserWindowsCurrentID];
  559. NSString *IDValue = [NSString stringWithFormat:@"%ld", ID];
  560. NSString *where = [NSString stringWithFormat:@"where %@=%@",bg_sqlKey(@"ID"),bg_sqlValue(IDValue)];
  561. NSArray *modelArr = [BaseModel bg_find:DB_BrowserWindows_TableName where:where];
  562. BaseModel *model = modelArr.firstObject;
  563. vc.model = model;
  564. [self presentViewController:vc animated:YES completion:^{
  565. }];
  566. });
  567. }else if ([title isEqualToString:NSLocalizedString(@"more_bookmark",nil)]) {
  568. HLog(@"书签");
  569. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  570. HWBookmarkViewController *vc = [[HWBookmarkViewController alloc] init];
  571. [self.navigationController pushViewController:vc animated:YES];
  572. });
  573. }else if ([title isEqualToString:NSLocalizedString(@"more_history",nil)]) {
  574. HLog(@"历史");
  575. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  576. HWHistoryViewController *vc = [[HWHistoryViewController alloc] init];
  577. [self.navigationController pushViewController:vc animated:YES];
  578. });
  579. }else if ([title isEqualToString:NSLocalizedString(@"more_set",nil)]) {
  580. HLog(@"设置");
  581. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  582. HWSetViewController *vc = [[HWSetViewController alloc] init];
  583. [self.navigationController pushViewController:vc animated:YES];
  584. });
  585. }else if ([title isEqualToString:NSLocalizedString(@"more_traceless",nil)]) {
  586. HLog(@"无痕");
  587. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  588. BOOL isNoTrackModel = [HWDataManager getBoolWithKey:Const_IsNoTrackModel];
  589. if (isNoTrackModel) {
  590. [[iToast makeText:NSLocalizedString(@"other_close_traceless",nil)] show];
  591. [HWDataManager setBoolWithKey:Const_IsNoTrackModel value:NO];
  592. }else {
  593. [[iToast makeText:NSLocalizedString(@"other_open_traceless",nil)] show];
  594. [HWDataManager setBoolWithKey:Const_IsNoTrackModel value:YES];
  595. }
  596. });
  597. }else if ([title isEqualToString:NSLocalizedString(@"more_refresh",nil)]) {
  598. HLog(@"刷新");
  599. [self.webView reload];
  600. }else if ([title isEqualToString:NSLocalizedString(@"more_share",nil)]) {
  601. HLog(@"分享");
  602. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  603. [self share];
  604. });
  605. }
  606. }
  607. - (void)share {
  608. //分享的标题
  609. NSString *textToShare = self.webView.title;
  610. if (self.shareTitle.length != 0) {
  611. textToShare = self.shareTitle;
  612. }
  613. //分享的图片
  614. UIImage *imageToShare = [UIImage imageNamed:@"logo_pic"];
  615. //分享的url
  616. NSURL *urlToShare = self.webView.URL;
  617. if (self.shareUrl.length != 0) {
  618. urlToShare = [NSURL URLWithString:self.shareUrl];
  619. }
  620. NSArray *activityItems = @[textToShare,imageToShare, urlToShare];
  621. UIActivityViewController *activityVC = [[UIActivityViewController alloc] initWithActivityItems:activityItems applicationActivities:nil];
  622. activityVC.excludedActivityTypes = @[UIActivityTypePrint,UIActivityTypePostToWeibo, UIActivityTypeCopyToPasteboard,UIActivityTypeAssignToContact,UIActivityTypeSaveToCameraRoll];
  623. [self presentViewController:activityVC animated:YES completion:nil];
  624. //分享之后的回调
  625. activityVC.completionWithItemsHandler = ^(UIActivityType _Nullable activityType, BOOL completed, NSArray * _Nullable returnedItems, NSError * _Nullable activityError) {
  626. if (completed) {
  627. HLog(@"分享 成功");
  628. } else {
  629. HLog(@"分享 取消");
  630. }
  631. };
  632. }
  633. #pragma mark 截图
  634. - (void)updateBrowserWindow {
  635. // 浏览器当前窗口索引ID
  636. NSInteger ID = [HWDataManager getIntegerWithKey:BrowserWindowsCurrentID];
  637. NSString *IDValue = [NSString stringWithFormat:@"%ld", ID];
  638. NSString *where = [NSString stringWithFormat:@"where %@=%@",bg_sqlKey(@"ID"),bg_sqlValue(IDValue)];
  639. NSArray *modelArr = [BaseModel bg_find:DB_BrowserWindows_TableName where:where];
  640. NSArray *dataArray = [BaseModel bg_findAll:DB_BrowserWindows_TableName];
  641. if (dataArray.count == 0) { // 无窗口
  642. BaseModel *model = [[BaseModel alloc] init];
  643. model.ID = 0;
  644. model.name = @"主页";
  645. // 更新URL
  646. model.webUrl = Const_HomeUrl;
  647. // 更新截图
  648. // UIImage *image = [self getScreenShotImage];
  649. // if (image) {
  650. // NSString *imageName = [NSString stringWithFormat:@"%ld", ID];
  651. // NSString *imageUrl = [HWDataManager writeScreenShotImageToLocal:image withName:imageName];
  652. // model.iconFile = imageUrl;
  653. // }
  654. // 更新数据库
  655. model.bg_tableName = DB_BrowserWindows_TableName;
  656. [model bg_saveOrUpdateAsync:^(BOOL isSuccess) {
  657. HLog(@"BaseModel更新: %@", isSuccess ? @"成功":@"失败");
  658. }];
  659. [HWDataManager setIntegerWithKey:BrowserWindowsCurrentID value:0];
  660. [self loadRequestURL:model.webUrl];
  661. }else if (modelArr.count == 0) { // 当前窗口已被删除 更新BrowserWindowsCurrentID
  662. BaseModel *lastModel = [BaseModel bg_lastObject:DB_BrowserWindows_TableName];
  663. [HWDataManager setIntegerWithKey:BrowserWindowsCurrentID value:lastModel.ID];
  664. [self loadRequestURL:lastModel.webUrl];
  665. }else { // 当前窗口加载页面 更新model
  666. BaseModel *model = modelArr.firstObject;
  667. model.ID = ID;
  668. model.name = self.webView.title;
  669. // 更新URL
  670. model.webUrl = self.webView.URL.absoluteString;
  671. // 更新截图
  672. // UIImage *image = [self getScreenShotImage];
  673. // if (image) {
  674. // NSString *imageName = [NSString stringWithFormat:@"%ld", ID];
  675. // NSString *imageUrl = [HWDataManager writeScreenShotImageToLocal:image withName:imageName];
  676. // model.iconFile = imageUrl;
  677. // }
  678. // 更新数据库
  679. model.bg_tableName = DB_BrowserWindows_TableName;
  680. [model bg_saveOrUpdateAsync:^(BOOL isSuccess) {
  681. HLog(@"BaseModel更新: %@", isSuccess ? @"成功":@"失败");
  682. }];
  683. }
  684. }
  685. /**WKWebView截图*/
  686. - (UIImage *)getScreenShotImage {
  687. UIScrollView *scrollView = self.webView.scrollView;
  688. // 1. 记录当前 scrollView 的偏移和位置
  689. CGPoint currentOffset = scrollView.contentOffset;
  690. CGRect currentFrame = scrollView.frame;
  691. scrollView.contentOffset = CGPointZero;
  692. // 2. 将 scrollView 展开为其实际内容的大小
  693. scrollView.frame = CGRectMake(0, 0, self.webView.frame.size.width, self.webView.frame.size.height);
  694. // 3. 第三个参数设置为 0 表示设置为屏幕的默认缩放因子
  695. UIGraphicsBeginImageContextWithOptions(scrollView.frame.size, YES, 0);
  696. [scrollView.layer renderInContext:UIGraphicsGetCurrentContext()];
  697. UIImage *snapshotImage = UIGraphicsGetImageFromCurrentImageContext();
  698. UIGraphicsEndImageContext();
  699. // 4. 重新设置 scrollView 的偏移和位置,还原现场
  700. scrollView.contentOffset = currentOffset;
  701. scrollView.frame = currentFrame;
  702. return snapshotImage;
  703. }
  704. #pragma mark 历史记录
  705. - (void)saveHistory {
  706. BOOL isNoTrackModel = [HWDataManager getBoolWithKey:Const_IsNoTrackModel];
  707. if (isNoTrackModel) {
  708. return;
  709. }
  710. HWHistoryModel *model = [[HWHistoryModel alloc] init];
  711. model.name = self.webView.title;
  712. model.webUrl = self.webView.URL.absoluteString;
  713. model.cTime = [iTools getNowTimeStamp];
  714. // 更新数据库
  715. model.bg_tableName = DB_Bookmark_History_TableName;
  716. [model bg_saveOrUpdateAsync:^(BOOL isSuccess) {
  717. HLog(@"HWHistoryModel 更新: %@", isSuccess ? @"成功":@"失败");
  718. }];
  719. }
  720. - (void)dealloc {
  721. [[NSNotificationCenter defaultCenter] removeObserver:self];
  722. }
  723. @end