HWWebViewController.m 33 KB

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