HWWebViewController.m 36 KB

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