HWWebViewController.m 35 KB

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