HWWebViewController.m 35 KB

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