HWWebViewController.m 34 KB

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