HWWebViewController.m 35 KB

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