HWWebViewController.m 31 KB

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