HWWebViewController.m 27 KB

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