HWWebViewController.m 33 KB

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