HWWebViewController.m 35 KB

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