HWWebViewController.m 35 KB

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