123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942 |
- //
- // HWWebViewController.m
- // Private-X
- //
- // Created by 余衡武 on 2022/3/9.
- //
- #import "HWWebViewController.h"
- #import <WebKit/WebKit.h>
- #import "HWWebViewController.h"
- #import "HWToolViewController.h"
- #import "HWAddBookmarkViewController.h"
- #import "HWBookmarkViewController.h"
- #import "HWSetViewController.h"
- #import "HWHistoryViewController.h"
- #import "HWHistoryModel.h"
- #import "iPhone.h"
- #import "connectDeviceManager.h"
- #import "RSATool.h"
- #import "customToastVew.h"
- @interface HWWebViewController ()<WKScriptMessageHandler,WKNavigationDelegate,WKUIDelegate,HWToolViewControllerDelete>{
- UIView *bgView;/*引导视图*/
- }
- // 底部工具条
- @property (nonatomic,strong) WKWebView *webView;
- @property (nonatomic,strong) UIProgressView *progressView;
- @property (nonatomic,strong) NSString *shareUrl;
- @property (nonatomic,strong) NSString *shareTitle;
- @property (nonatomic,strong) NSString *shareImage;
- @end
- @implementation HWWebViewController
- -(void)viewWillAppear:(BOOL)animated
- {
- [super viewWillAppear:animated];
-
- // addScriptMessageHandler
- [self.webView.configuration.userContentController addScriptMessageHandler:self name:@"setShareInfo"];
- [self.webView.configuration.userContentController addScriptMessageHandler:self name:@"openShare"];
- [self.webView.configuration.userContentController addScriptMessageHandler:self name:@"openApp"];
-
- // 添加KVO监听
- [self.webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew
- context:nil];
- [self.webView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew
- context:nil];
-
- [[netWorkManager shareInstance] RefreshThridMsg];
- }
- - (void)viewDidAppear:(BOOL)animated{
- [super viewDidAppear:animated];
-
- [self.webView evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id result, NSError *error) {
- if (error == noErr) {
- if ([result isKindOfClass:[NSString class]]) {
- NSString *userAgent = result;
- NSDictionary *infoDic = [[NSBundle mainBundle] infoDictionary];
- NSString *appVersion = [infoDic objectForKey:@"CFBundleShortVersionString"];
-
- 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]];
- [self.webView setCustomUserAgent:newUserAgent];
- }
- }
- }];
-
- // /*判断是否有安装WhatsApp*/
- // if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"whatsapp://"]]){
- // NSLog(@"\n---有安装 whatsApp---");
- // [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"whatsapp://"]];
- // }else{
- // NSLog(@"\n+++没有安装 whatsApp+++");
- // }
- //
- // if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"mqq://"]]){
- // NSLog(@"\n---有安装 qq---");
- // }else{
- // NSLog(@"\n+++没有安装 qq+++");
- // }
- }
- - (void)viewWillDisappear:(BOOL)animated
- {
- [super viewWillDisappear:animated];
-
- // addScriptMessageHandler 很容易导致循环引用 必须手动移除 因此这里要记得移除handlers
- [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"setShareInfo"];
- [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"openShare"];
- [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"openApp"];
-
- // 移除KVO监听
- [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
- [self.webView removeObserver:self forKeyPath:@"title"];
- }
- - (void)viewDidLoad {
- [super viewDidLoad];
-
- [self drawView];
-
- [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateBrowserWindow) name:WebviewReloadNotification object:nil];
-
- if (self.pwd.length > 0){
- BOOL haveOpenMask = [HWDataManager getBoolWithKey:Const_Mask_View_Open_Web_Tips];
- if (haveOpenMask == NO){
- [self addGuideView];
- }
- }
- }
- - (void)addGuideView{
- bgView = [[UIView alloc] init];
- [bgView setBackgroundColor:HW000000Color60];
- [self.view addSubview:bgView];
- [bgView mas_makeConstraints:^(MASConstraintMaker *make) {
- make.left.mas_equalTo(0);
- make.bottom.mas_equalTo(0);
- make.right.mas_equalTo(0);
- make.top.mas_equalTo(0);
- }];
-
-
- UIView *tipsInputView = [[UIView alloc] init];
- [tipsInputView setBackgroundColor:[UIColor whiteColor]];
- [tipsInputView.layer setCornerRadius:5];
- [tipsInputView.layer setBorderWidth:1];
- [bgView addSubview:tipsInputView];
- [tipsInputView mas_makeConstraints:^(MASConstraintMaker *make) {
- make.left.mas_equalTo(10);
- make.height.mas_equalTo(36);
- make.right.mas_equalTo(-10);
- make.top.equalTo(self.navigationBar.textField.mas_top).offset(-1);
- }];
-
- /*箭头视图*/
- UIImageView *flagImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"guide_open_calcu_flag1"]];
- [bgView addSubview:flagImageView];
- [flagImageView mas_makeConstraints:^(MASConstraintMaker *make) {
- make.right.mas_equalTo(-118.f);
- make.height.mas_equalTo(67);
- make.width.mas_equalTo(22);
- make.top.equalTo(self.navigationBar.mas_bottom);
- }];
-
- /*不可点击btn*/
- UIButton *unableBtn = [[UIButton alloc] init];
- unableBtn.frame = CGRectMake(0, 0, 295, 64);
- NSString * curStr = NSLocalizedString(@"guide_set_open_web_guide_tips",nil);
- CGFloat curHeight = [curStr boundingRectWithSize:CGSizeMake(295 - 20 , 1000) options:(NSStringDrawingUsesLineFragmentOrigin) attributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:14.f]} context:nil].size.height;
-
- if(curHeight < 50){
- curHeight = 50;
- }
- else{
- curHeight += 20;
- }
-
- // gradient
- CAGradientLayer *gl = [CAGradientLayer layer];
- gl.frame = CGRectMake(0,0,295,curHeight);
- gl.startPoint = CGPointMake(0, 0.5);
- gl.endPoint = CGPointMake(1, 0.5);
- gl.colors = @[(__bridge id)HW0CDEFDColor.CGColor, (__bridge id)HW058DFBColor.CGColor];
- gl.locations = @[@(0), @(1.0f)];
-
- [unableBtn.layer addSublayer:gl];
- [unableBtn setUserInteractionEnabled:NO];
- [unableBtn setTitle:curStr forState:(UIControlStateNormal)];
- [unableBtn setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
- [unableBtn.titleLabel setFont:[UIFont systemFontOfSize:14.f]];
- [unableBtn.titleLabel setNumberOfLines:0];
- [unableBtn.layer setCornerRadius:curHeight/2.0];
- unableBtn.clipsToBounds = YES;
- [bgView addSubview:unableBtn];
- [unableBtn mas_makeConstraints:^(MASConstraintMaker *make) {
- make.right.mas_equalTo(-20*AUTOSCALE);
- make.width.mas_equalTo(295);
- make.top.equalTo(flagImageView.mas_bottom).offset(-8);
- make.height.mas_equalTo(curHeight);
- }];
- unableBtn.contentEdgeInsets = UIEdgeInsetsMake(0,10, 0, 10);
-
- UIButton *knowBtn = [[UIButton alloc] init];
- [knowBtn setBackgroundColor:[UIColor clearColor]];
- [knowBtn.layer setCornerRadius:18.f];
- [knowBtn.layer setBorderColor:HWFFFFFFColor.CGColor];
- [knowBtn.layer setBorderWidth:1];
- [knowBtn setTitle:NSLocalizedString(@"guide_set_pwd_guide_know",nil) forState:(UIControlStateNormal)];
- [knowBtn setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
- [knowBtn.titleLabel setFont:[UIFont systemFontOfSize:16]];
- [bgView addSubview:knowBtn];
- [knowBtn mas_makeConstraints:^(MASConstraintMaker *make) {
- make.right.mas_equalTo(-29*AUTOSCALE);
- make.width.mas_equalTo(120);
- make.top.equalTo(unableBtn.mas_bottom).offset(15);
- make.height.mas_equalTo(36.f);
- }];
- [knowBtn addTarget:self
- action:@selector(knowBtnPressed)
- forControlEvents:(UIControlEventTouchUpInside)];
- }
- - (void)knowBtnPressed{
- [bgView removeFromSuperview];
- [HWDataManager setBoolWithKey:Const_Mask_View_Open_Web_Tips value:YES];
- }
- - (void)drawView {
-
- self.view.backgroundColor = [UIColor hwColor:@"#1C1C1E"];
- [self.toolBar setHidden:YES];
- // WKWebView
- WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
- self.webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, 0, 0) configuration:config];
- // self.webView.backgroundColor = HWBGColor;
- self.webView.navigationDelegate = self;
- self.webView.UIDelegate = self;
- self.webView.backgroundColor = [UIColor hwColor:@"#1C1C1E"];
- self.webView.scrollView.backgroundColor = [UIColor hwColor:@"#1C1C1E"];
- self.webView.opaque = NO;
- self.webView.scrollView.bounces = NO;
- self.webView.allowsBackForwardNavigationGestures = YES; //开了支持滑动返回
- // self.webView. = NO;
- [self.view addSubview:self.webView];
-
- CGFloat curWidth = SCREEN_W;
- CGFloat curHeight = SCREEN_H;
- if(curWidth > curHeight){
- curWidth = SCREEN_H;
- curHeight = SCREEN_W;
- }
-
- [self.webView mas_makeConstraints:^(MASConstraintMaker *make) {
- make.top.mas_equalTo(self.navigationBar.mas_bottom);
- make.left.mas_equalTo(0);
- make.width.mas_equalTo(curWidth);
- //make.bottom.mas_equalTo(self.toolBar.mas_top);
- make.height.mas_equalTo(curHeight - self.navigationBar.hw_h);
- }];
-
-
- //进度条
- self.progressView = [[UIProgressView alloc] init];
- [self.navigationBar.textField addSubview:self.progressView];
- [self.progressView mas_makeConstraints:^(MASConstraintMaker *make) {
- make.bottom.mas_equalTo(0);
- make.left.mas_equalTo(0);
- make.width.mas_equalTo(SCREEN_W);
- make.height.mas_offset(2);
- }];
-
-
- // 加载网页
- if (self.webUrl.length == 0) { // 百度
-
- [self loadRequestURL:@"https://www.baidu.com/"];
-
- }else if ([self.webUrl containsString:@"https://"] ||
- [self.webUrl containsString:@"http://"]) { // 加载网页
-
- [self loadRequestURL:self.webUrl];
-
- }else { // 搜索
-
- NSString *text = [NSString stringWithFormat:@"https://www.baidu.com/s?wd=%@",self.webUrl];
- text = [text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
- [self loadRequestURL:text];
- }
-
- }
- - (void)loadRequestURL:(NSString *)urlString {
-
- NSURL *url = [NSURL URLWithString:urlString];
- NSURLRequest *request = [NSURLRequest requestWithURL:url];
- [self.webView loadRequest:request];
-
- [self.view addSubview:self.webView];
- }
- #pragma mark - HWSearchBarDelegate
- - (void)searchBarWithText:(NSString *)text {
- HLog(@"搜索:%@", text)
-
- if(text.length == 4){
- [self verifyPwdFun:text];
- }
-
- // if ([_pwd isEqualToString:text] && (_pwd.length == 4)){
- // [connectDeviceManager shareInstance].isFirstInputPwdDone = YES;
- //
- // [self.view removeFromSuperview];
- // [[NSNotificationCenter defaultCenter] postNotificationName:ShowImgAndVoiceNotification object:nil];
- // }
-
- if (text.length != 0) {
- if ([text hasPrefix:@"https://"] ||
- [text hasPrefix:@"http://"]) {
- [self loadRequestURL:text];
- }else {
- text = [NSString stringWithFormat:@"https://www.baidu.com/s?wd=%@",text];
- text = [text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
- [self loadRequestURL:text];
- }
- }
- }
- - (void)searchBarChangeText:(NSString *)text{
- HLog(@"\n----searchBarChangeText===%@-------",text);
- if (text.length == 4){
- [self verifyPwdFun:text];
- }
- }
- #pragma mark 验证密码是否正确
- -(void)verifyPwdFun:(NSString*)text{
- /*先判断本地有无设备 无设备时需要先扫码添加设备*/
- NSDictionary *deviceDict = [HWDataManager getObjectWithKey:Const_Have_Add_Device];
- if (deviceDict && [[deviceDict allKeys] containsObject:Const_Have_Add_Device_SN]){
- //有设备了先去做链接准备 // 80bec9c5
- NSString *SNStr = deviceDict[@"Const_Have_Add_Device_SN"];
-
- if(SNStr){
- NSString *curPwd = nil;
- NSString*desPwdStr = nil;
-
- if(ksharedAppDelegate.DeviceThirdIdMod.data.password
- && ksharedAppDelegate.DeviceThirdIdMod.data.password.length > 0){
- curPwd = ksharedAppDelegate.DeviceThirdIdMod.data.password;
- desPwdStr = [RSATool AES128Decrypt:curPwd key:AESCODEKEEYY];
- }
- else{
- if(deviceDict && [[deviceDict allKeys] containsObject:Const_Have_Add_Device_PWD])
- {
- desPwdStr = deviceDict[Const_Have_Add_Device_PWD];
- }
- }
-
- if ([desPwdStr isEqualToString:text]){
-
- HLog(@"输入密码正确")
-
- if([AFNetworkReachabilityManager sharedManager].networkReachabilityStatus == AFNetworkReachabilityStatusNotReachable)
- {
- //[[iToast makeText:NSLocalizedString(@"phone_network_fail_Tips",nil)] show];
- customToastVew *view = [customToastVew makeText:NSLocalizedString(@"phone_network_fail_Tips",nil)];
- [view show];
- [self.view addSubview:view];
-
- return;
- }
-
- ksharedAppDelegate.isFirstInputPwdDone = YES;
- ksharedAppDelegate.isDidShowPwdType = NO;
- [self.view removeFromSuperview];
- //被别的设备挤下线 重新链接 如果是链接中 走这个函数会被return
- if(![webRtcManager shareManager].isWaitShowLogoutAlert){
- [[webRtcManager shareManager] beginToLinkWebRtcFun];
- dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
- [[NSNotificationCenter defaultCenter] postNotificationName:didInputPWDNotification object:nil];
- });
- }
- }
- else if([text isEqualToString:keyToForgetPwd]){
- [[NSNotificationCenter defaultCenter] postNotificationName:forgetPwdNotification object:nil];
- }
- }
- }
-
- }
- #pragma mark - HWToolBarDelegate
- - (void)backBtnDidClick {
- HLog(@"后退");
- if ([self.webView canGoBack]) {
- [self.webView goBack];
- }else {
- [self.navigationController popViewControllerAnimated:YES];
- }
-
- // 更新缓存
- dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
- [self updateBrowserWindow];
- });
- }
- - (void)forwardBtnDidClick {
- HLog(@"前进");
- if ([self.webView canGoForward]) {
- [self.webView goForward];
- }
-
- // 更新缓存
- dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
- [self updateBrowserWindow];
- });
- }
- #pragma mark- 监听加载进度
- - (void)observeValueForKeyPath:(NSString *)keyPath
- ofObject:(id)object
- change:(NSDictionary<NSString *,id> *)change
- context:(void *)context
- {
- HLog(@"加载进度:%.2f", self.webView.estimatedProgress);
-
- NSArray *arrViewControllers = self.navigationController.viewControllers;
- NSInteger index = [arrViewControllers indexOfObject:self];
-
- self.toolBar.backBtn.enabled = [self.webView canGoBack] || index > 0;
- self.toolBar.forwardBtn.enabled = [self.webView canGoForward];
-
- if ([keyPath isEqualToString:@"estimatedProgress"]) {
- self.progressView.progress = self.webView.estimatedProgress;
- // 加载完成
- if (self.webView.estimatedProgress >= 1.0f ) {
-
- [UIView animateWithDuration:0.25f animations:^{
- self.progressView.alpha = 0.0f;
- self.progressView.progress = 0.0f;
- }];
-
- }else{
- self.progressView.alpha = 1.0f;
-
- // 记录历史
- [self saveHistory];
- // 更新缓存
- dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
- [self updateBrowserWindow];
- });
- }
- }else if ([keyPath isEqualToString:@"title"]) {
-
- if (object == self.webView) {
-
- // [self.navigationBar.textField setText:self.webView.title];
- self.navigationBar.searchImageView.hidden = self.webView.title.length != 0;
- self.navigationBar.searchPlaceHolder.hidden = self.webView.title.length != 0;
- } else {
-
- [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
- }
- }
- }
- #pragma mark 事件代理
- // 页面开始加载时调用
- -(void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{
-
- self.shareTitle = @"";
- self.shareUrl = @"";
- self.shareImage = @"";
-
- [self showWebView0];
- }
- // 当内容开始返回时调用
- - (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation{
-
- }
- // 页面加载完成之后调用
- - (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{//这里修改导航栏的标题,动态改变
-
- HLog(@"webViewtitle:%@",webView.title);
-
- // [self.webView evaluateJavaScript:@"document.getElementsByTagName('body')[0].style.background='#2D2F35'" completionHandler:nil];
- //
- //// if (webView.title && webView.title.length > 0 ) {
- //// [self.navigationBar.textField setText:webView.title];
- //// }
-
- [self removeNewIndicator];
-
- // 更新缓存
- dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
- [self updateBrowserWindow];
- });
-
- [self showWebView1];
- }
- // 页面加载失败时调用
- - (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation{
- [self removeNewIndicator];
-
- // [self.webView evaluateJavaScript:@"document.getElementsByTagName('body')[0].style.background='#2D2F35'" completionHandler:nil];
-
- // 更新缓存
- dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
- [self updateBrowserWindow];
- });
-
- [self showWebView3];
- }
- #pragma mark - 解决wkwebView闪白问题
- // 解决wkwebView闪白问题
- - (void)showWebView0 {
-
- self.webView.hidden = YES;
-
- [self performSelector:@selector(showWebView1) withObject:self afterDelay:1];
-
- [self showNewIndicatorWithCanBack:YES canTouch:NO];
- }
-
- // 1改变网页内容背景颜色
- - (void)showWebView1 {
- [self performSelector:@selector(showWebView2) withObject:self afterDelay:0.2];
- }
- // 2加载成功
- - (void)showWebView2 {
- [self removeNewIndicator];
- self.webView.hidden = NO;
- }
- // 3加载失败
- - (void)showWebView3 {
- [self removeNewIndicator];
- }
- // 接收到服务器跳转请求之后再执行
- - (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation{
-
- }
- // 在收到响应后,决定是否跳转
- - (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler{
-
- // HLog(@"%@",webView);
- // HLog(@"%@",navigationResponse);
-
- WKNavigationResponsePolicy actionPolicy = WKNavigationResponsePolicyAllow;
- //这句是必须加上的,不然会异常
- decisionHandler(actionPolicy);
-
- NSArray *arrViewControllers = self.navigationController.viewControllers;
- NSInteger index = [arrViewControllers indexOfObject:self];
-
- self.toolBar.backBtn.enabled = [self.webView canGoBack] || index > 0;
- self.toolBar.forwardBtn.enabled = [self.webView canGoForward];
-
- // if (webView.title && webView.title.length > 0 ) {
- // [self.navigationBar.textField setText:webView.title];
- // }
- }
- // 在发送请求之前,决定是否跳转
- - (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
-
- HLog(@"URL=======%@", navigationAction.request.URL);
- HLog(@"URL.scheme=======%@", navigationAction.request.URL.scheme);
-
- if (navigationAction.targetFrame == nil) {
- [webView loadRequest:navigationAction.request];
- }
- if (navigationAction.navigationType==WKNavigationTypeBackForward) {//判断是返回类型
-
-
- }
-
- //这句是必须加上的,不然会异常
- decisionHandler(WKNavigationActionPolicyAllow);
-
- NSString *url = navigationAction.request.URL.absoluteString;
- HLog(@"支付url:%@", url);
- if ([url containsString:@"weixin:"]) {
- [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url] options:@{} completionHandler:^(BOOL success) {
-
- if (!success) { // 打开微信失败
- [self toShowNoWX];
- }
-
- }];
-
- }else if ([url containsString:@"alipay:"]) {
-
- [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url] options:@{} completionHandler:^(BOOL success) {
-
- if (!success) { // 打开支付宝失败
- [self toShowNoZFB];
- }
-
- }];
- }else if ([url containsString:@"https://jq.qq.com/"]) { // 加入QQ群
-
- [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url] options:@{} completionHandler:^(BOOL success) {
-
- }];
- }
- }
- - (void)toShowNoWX {
- NSString *tipsStr = @"您的手机未安装微信,请先安装后再进行支付或者选择其他支付方式";
- UIAlertAction *sureAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"other_confirm",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
- }];
- [sureAction setValue:[UIColor hwColor:@"#FFFFFF"] forKey:@"titleTextColor"];//iOS8.3
-
-
- UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:tipsStr message:@"" preferredStyle:(UIAlertControllerStyleAlert)];
- alertVC.overrideUserInterfaceStyle = UIUserInterfaceStyleDark;
-
- [alertVC addAction:sureAction];
- [self presentViewController:alertVC animated:YES completion:^{
-
- }];
- }
- - (void)toShowNoZFB {
- NSString *tipsStr = NSLocalizedString(@"no_air_pay_tips",nil);
- UIAlertAction *sureAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"other_confirm",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
- }];
- [sureAction setValue:[UIColor hwColor:@"#FFFFFF"] forKey:@"titleTextColor"];//iOS8.3
-
-
- UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:tipsStr message:@"" preferredStyle:(UIAlertControllerStyleAlert)];
- alertVC.overrideUserInterfaceStyle = UIUserInterfaceStyleDark;
-
- [alertVC addAction:sureAction];
- [self presentViewController:alertVC animated:YES completion:^{
-
- }];
- }
- #pragma mark - WKScriptMessageHandler
- - (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
- // HLog(@"%@",NSStringFromSelector(_cmd));
- // HLog(@"%@",message);
- HLog(@"%@",message.body);
- HLog(@"%@",message.name);
- //这个是注入JS代码后的处理效果,尽管html已经有实现了,但是没用,还是执行JS中的实现
- if ([message.name isEqualToString:@"setShareInfo"]) {
- HLog(@"%@",message.body);
- HLog(@"%@",message.name);
- NSDictionary *bodyDict = message.body;
- if ([[bodyDict allKeys] containsObject:@"title"]) {
- self.shareTitle = [bodyDict objectForKey:@"title"];
- }
- if ([[bodyDict allKeys] containsObject:@"gotoUrl"]) {
- self.shareUrl = [bodyDict objectForKey:@"gotoUrl"];
- }
- if ([[bodyDict allKeys] containsObject:@"shareImg"]) {
- self.shareImage = [bodyDict objectForKey:@"shareImg"];
- }
- }else if ([message.name isEqualToString:@"openShare"]) {
-
- NSDictionary *bodyDict = message.body;
- if ([[bodyDict allKeys] containsObject:@"title"]) {
- self.shareTitle = [bodyDict objectForKey:@"title"];
- }
- if ([[bodyDict allKeys] containsObject:@"gotoUrl"]) {
- self.shareUrl = [bodyDict objectForKey:@"gotoUrl"];
- }
- if ([[bodyDict allKeys] containsObject:@"shareImg"]) {
- self.shareImage = [bodyDict objectForKey:@"shareImg"];
- }
-
- // 分享
- dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
- [self share];
- });
- }else if ([message.name isEqualToString:@"openApp"]) {
-
- NSString *openUrl = [NSString stringWithFormat:@"%@",message.body];
-
-
- if ([openUrl containsString:@"whatsapp"]){
-
- /*判断是否有安装WhatsApp*/
- if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"whatsapp://"]]){
- NSLog(@"\n---有安装 whatsApp---");
- [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"whatsapp://"]];
- }else{
- [[iToast makeText:NSLocalizedString(@"app_install_whatsApp_tips",nil)] show];
- }
- return;
- }
-
- [[UIApplication sharedApplication] openURL:[NSURL URLWithString:openUrl] options:@{} completionHandler:^(BOOL success) {
-
- }];
-
- }else {
- HLog(@"其他类型");
- }
- }
- - (void)toolBtnDidClick {
- HLog(@"工具");
- HWToolViewController *vc = [[HWToolViewController alloc] init];
- vc.modalPresentationStyle = UIModalPresentationCustom;
- vc.delegate = self;
- vc.isSetUnavailable = NO;
- [self presentViewController:vc animated:YES completion:^{
- vc.view.superview.backgroundColor = RGBACOLOR(0, 0, 0, 0.25);
- }];
- }
- #pragma mark HWToolViewControllerDelete
- - (void)toolDidClickItem:(NSString *)title {
-
- if ([title isEqualToString:NSLocalizedString(@"more_add_bookmark",nil)]) {
- HLog(@"添加书签");
- dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
- HWAddBookmarkViewController *vc = [[HWAddBookmarkViewController alloc] init];
- // BaseModel *model = [[BaseModel alloc] init];
- NSInteger ID = [HWDataManager getIntegerWithKey:BrowserWindowsCurrentID];
- NSString *IDValue = [NSString stringWithFormat:@"%ld", ID];
- NSString *where = [NSString stringWithFormat:@"where %@=%@",bg_sqlKey(@"ID"),bg_sqlValue(IDValue)];
- NSArray *modelArr = [BaseModel bg_find:DB_BrowserWindows_TableName where:where];
- BaseModel *model = modelArr.firstObject;
- vc.model = model;
- [self presentViewController:vc animated:YES completion:^{
-
- }];
- });
- }else if ([title isEqualToString:NSLocalizedString(@"more_bookmark",nil)]) {
- HLog(@"书签");
- dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
- HWBookmarkViewController *vc = [[HWBookmarkViewController alloc] init];
- [self.navigationController pushViewController:vc animated:YES];
- });
- }else if ([title isEqualToString:NSLocalizedString(@"more_history",nil)]) {
- HLog(@"历史");
- dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
- HWHistoryViewController *vc = [[HWHistoryViewController alloc] init];
- [self.navigationController pushViewController:vc animated:YES];
- });
- }else if ([title isEqualToString:NSLocalizedString(@"more_set",nil)]) {
- HLog(@"设置");
- dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
- HWSetViewController *vc = [[HWSetViewController alloc] init];
- [self.navigationController pushViewController:vc animated:YES];
- });
- }else if ([title isEqualToString:NSLocalizedString(@"more_traceless",nil)]) {
- HLog(@"无痕");
- dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
-
- BOOL isNoTrackModel = [HWDataManager getBoolWithKey:Const_IsNoTrackModel];
- if (isNoTrackModel) {
- [[iToast makeText:NSLocalizedString(@"other_close_traceless",nil)] show];
- [HWDataManager setBoolWithKey:Const_IsNoTrackModel value:NO];
- }else {
- [[iToast makeText:NSLocalizedString(@"other_open_traceless",nil)] show];
- [HWDataManager setBoolWithKey:Const_IsNoTrackModel value:YES];
- }
- });
-
- }else if ([title isEqualToString:NSLocalizedString(@"more_refresh",nil)]) {
- HLog(@"刷新");
- [self.webView reload];
- }else if ([title isEqualToString:NSLocalizedString(@"more_share",nil)]) {
- HLog(@"分享");
- dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
- [self share];
- });
- }
- }
- - (void)share {
-
- //分享的标题
- NSString *textToShare = self.webView.title;
- if (self.shareTitle.length != 0) {
- textToShare = self.shareTitle;
- }
- //分享的图片
- UIImage *imageToShare = [UIImage imageNamed:@"logo_pic"];
-
- //分享的url
- NSURL *urlToShare = self.webView.URL;
- if (self.shareUrl.length != 0) {
- urlToShare = [NSURL URLWithString:self.shareUrl];
- }
- NSArray *activityItems = @[textToShare,imageToShare, urlToShare];
-
- UIActivityViewController *activityVC = [[UIActivityViewController alloc] initWithActivityItems:activityItems applicationActivities:nil];
- activityVC.excludedActivityTypes = @[UIActivityTypePrint,UIActivityTypePostToWeibo, UIActivityTypeCopyToPasteboard,UIActivityTypeAssignToContact,UIActivityTypeSaveToCameraRoll];
-
- [self presentViewController:activityVC animated:YES completion:nil];
-
- //分享之后的回调
- activityVC.completionWithItemsHandler = ^(UIActivityType _Nullable activityType, BOOL completed, NSArray * _Nullable returnedItems, NSError * _Nullable activityError) {
- if (completed) {
- HLog(@"分享 成功");
- } else {
- HLog(@"分享 取消");
- }
- };
- }
- #pragma mark 截图
- - (void)updateBrowserWindow {
-
- // 浏览器当前窗口索引ID
- NSInteger ID = [HWDataManager getIntegerWithKey:BrowserWindowsCurrentID];
- NSString *IDValue = [NSString stringWithFormat:@"%ld", ID];
- NSString *where = [NSString stringWithFormat:@"where %@=%@",bg_sqlKey(@"ID"),bg_sqlValue(IDValue)];
- NSArray *modelArr = [BaseModel bg_find:DB_BrowserWindows_TableName where:where];
-
- NSArray *dataArray = [BaseModel bg_findAll:DB_BrowserWindows_TableName];
-
- if (dataArray.count == 0) { // 无窗口
-
- BaseModel *model = [[BaseModel alloc] init];
- model.ID = 0;
- model.name = @"主页";
- // 更新URL
- model.webUrl = Const_HomeUrl;
-
- // 更新截图
- // UIImage *image = [self getScreenShotImage];
- // if (image) {
- // NSString *imageName = [NSString stringWithFormat:@"%ld", ID];
- // NSString *imageUrl = [HWDataManager writeScreenShotImageToLocal:image withName:imageName];
- // model.iconFile = imageUrl;
- // }
- // 更新数据库
- model.bg_tableName = DB_BrowserWindows_TableName;
- [model bg_saveOrUpdateAsync:^(BOOL isSuccess) {
- HLog(@"BaseModel更新: %@", isSuccess ? @"成功":@"失败");
- }];
-
- [HWDataManager setIntegerWithKey:BrowserWindowsCurrentID value:0];
-
- [self loadRequestURL:model.webUrl];
- }else if (modelArr.count == 0) { // 当前窗口已被删除 更新BrowserWindowsCurrentID
-
- BaseModel *lastModel = [BaseModel bg_lastObject:DB_BrowserWindows_TableName];
-
- [HWDataManager setIntegerWithKey:BrowserWindowsCurrentID value:lastModel.ID];
-
- [self loadRequestURL:lastModel.webUrl];
-
- }else { // 当前窗口加载页面 更新model
-
- BaseModel *model = modelArr.firstObject;
- model.ID = ID;
- model.name = self.webView.title;
- // 更新URL
- model.webUrl = self.webView.URL.absoluteString;
- // 更新截图
- // UIImage *image = [self getScreenShotImage];
- // if (image) {
- // NSString *imageName = [NSString stringWithFormat:@"%ld", ID];
- // NSString *imageUrl = [HWDataManager writeScreenShotImageToLocal:image withName:imageName];
- // model.iconFile = imageUrl;
- // }
- // 更新数据库
- model.bg_tableName = DB_BrowserWindows_TableName;
- [model bg_saveOrUpdateAsync:^(BOOL isSuccess) {
- HLog(@"BaseModel更新: %@", isSuccess ? @"成功":@"失败");
- }];
- }
- }
- /**WKWebView截图*/
- - (UIImage *)getScreenShotImage {
-
- UIScrollView *scrollView = self.webView.scrollView;
- // 1. 记录当前 scrollView 的偏移和位置
- CGPoint currentOffset = scrollView.contentOffset;
- CGRect currentFrame = scrollView.frame;
- scrollView.contentOffset = CGPointZero;
- // 2. 将 scrollView 展开为其实际内容的大小
- scrollView.frame = CGRectMake(0, 0, self.webView.frame.size.width, self.webView.frame.size.height);
- // 3. 第三个参数设置为 0 表示设置为屏幕的默认缩放因子
- UIGraphicsBeginImageContextWithOptions(scrollView.frame.size, YES, 0);
- [scrollView.layer renderInContext:UIGraphicsGetCurrentContext()];
- UIImage *snapshotImage = UIGraphicsGetImageFromCurrentImageContext();
- UIGraphicsEndImageContext();
- // 4. 重新设置 scrollView 的偏移和位置,还原现场
- scrollView.contentOffset = currentOffset;
- scrollView.frame = currentFrame;
- return snapshotImage;
- }
- #pragma mark 历史记录
- - (void)saveHistory {
-
- BOOL isNoTrackModel = [HWDataManager getBoolWithKey:Const_IsNoTrackModel];
- if (isNoTrackModel) {
- return;
- }
- HWHistoryModel *model = [[HWHistoryModel alloc] init];
- model.name = self.webView.title;
- model.webUrl = self.webView.URL.absoluteString;
- model.cTime = [iTools getNowTimeStamp];
-
- // 更新数据库
- model.bg_tableName = DB_Bookmark_History_TableName;
- [model bg_saveOrUpdateAsync:^(BOOL isSuccess) {
- HLog(@"HWHistoryModel 更新: %@", isSuccess ? @"成功":@"失败");
- }];
- }
- - (void)dealloc {
- [[NSNotificationCenter defaultCenter] removeObserver:self];
- }
- @end
|