HWWebViewController.m 27 KB

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