HWWebViewController.m 33 KB

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