123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407 |
- //
- // KDPWebInteractionVC.m
- // KuDianProject
- //
- // Created by 学丽 on 2019/7/9.
- // Copyright © 2019 KDP. All rights reserved.
- //
- #import "KDPWebInteractionVC.h"
- #import <WebKit/WebKit.h>
- #import <WebKit/WebKit.h>
- #import "WYWeakScriptMessageDelegate.h"
- #import <JavaScriptCore/JavaScriptCore.h>
- static NSString *refresh_h5 = @"refresh_h5";
- static NSString *app_h5_get_token = @"app_h5_get_token";//获取token
- static NSString *app_h5_save_message=@"app_h5_save_message";
- static NSString *app_h5_get_message=@"app_h5_get_message";
- static NSString *app_h5_to_goodsdetail=@"app_h5_to_goodsdetail";
- static NSString *kd_h5_open_goodDetail=@"kd_h5_open_goodDetail";
- @interface KDPWebInteractionVC ()<WKUIDelegate, WKNavigationDelegate,WKScriptMessageHandler>
- @property (nonatomic, strong) WKWebView *webInterView;
- /** 加载进度条 */
- @property (nonatomic, strong) UIProgressView *progressView;
- @property (nonatomic, strong) UIButton *closeButton;
- @property (nonatomic, strong) UIButton *refreshButton;
- @end
- @implementation KDPWebInteractionVC
- - (void)viewDidLoad {
- [super viewDidLoad];
- [self addNotification];
- [self configNavigationBar];
- [self addUserhandler];
- [self loadRequest];
- }
- - (void)addNotification {
- [[NSNotificationCenter defaultCenter] addObserver:self
- selector:@selector(updateSelectorWithH5)
- name:UIApplicationDidBecomeActiveNotification object:nil];
- [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(endFullScreen) name:UIWindowDidBecomeHiddenNotification object:nil];
- }
- //处理web视频全屏播放时 状态栏消失
- - (void)endFullScreen {
- [[UIApplication sharedApplication]setStatusBarHidden:false animated:false];
- }
- - (void)configNavigationBar {
-
- self.view.backgroundColor = [UIColor whiteColor];
- [self.view addSubview:self.webInterView];
- [self.view addSubview:self.progressView];
- [self.navBar addleftReturnButton:self selector:@selector(backAction)];
-
-
- if (@available(iOS 11.0, *)) {
- self.webInterView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;//UIScrollView也适用
- }else {
- self.automaticallyAdjustsScrollViewInsets = NO;
- }
- }
- - (void)addUserhandler {
- [[self.webInterView configuration].userContentController addScriptMessageHandler:[[WYWeakScriptMessageDelegate alloc] initWithDelegate:self] name:app_h5_get_token];
- [[self.webInterView configuration].userContentController addScriptMessageHandler:[[WYWeakScriptMessageDelegate alloc] initWithDelegate:self] name:app_h5_save_message];
- [[self.webInterView configuration].userContentController addScriptMessageHandler:[[WYWeakScriptMessageDelegate alloc] initWithDelegate:self] name:app_h5_get_message];
- [[self.webInterView configuration].userContentController addScriptMessageHandler:[[WYWeakScriptMessageDelegate alloc] initWithDelegate:self] name:app_h5_to_goodsdetail];
-
- [[self.webInterView configuration].userContentController addScriptMessageHandler:[[WYWeakScriptMessageDelegate alloc] initWithDelegate:self] name:kd_h5_open_goodDetail];
- }
- #pragma mark --- WKScriptMessageHandler
- - (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
- if ([message.name isEqualToString:app_h5_get_token]){
- //传token给js
- [self sendUserTokenToJS:message];
- }else if ([message.name isEqualToString:app_h5_save_message])
- {
- [self saveLocal:message];
- }else if ([message.name isEqualToString:app_h5_get_message])
- {
- [self sendmessageToJS:message];
- }else if ([message.name isEqualToString:app_h5_to_goodsdetail])
- {//跳转详情
- [self getGoodDetail:message];
- }else if ([message.name isEqualToString:kd_h5_open_goodDetail])
- {
- //跳转详情
- [self JumpGoodDetail:message];
- }
- }
- #pragma mark--跳转详情
- -(void)JumpGoodDetail:(WKScriptMessage *)message
- {
- NSDictionary *dict = [KDPublicMethod dictionaryWithJsonString:message.body];
- KDPGoodsModel *model =[[KDPGoodsModel alloc]init];
- model.goods_id = [NSString stringWithFormat:@"%@",dict[@"goodsid"]];
- KDPGoodDetailVC *detailVC = [[KDPGoodDetailVC alloc] init];
- detailVC.model = model;
- [self.navigationController pushViewController:detailVC animated:YES];
- }
- -(void)getGoodDetail:(WKScriptMessage *)message
- {
- NSDictionary *dict = [KDPublicMethod dictionaryWithJsonString:message.body];
- KDPGoodsModel *model =[[KDPGoodsModel alloc]init];
- model.goods_id = [NSString stringWithFormat:@"%@",dict[@"goodsId"]];
- KDPGoodDetailVC *detailVC = [[KDPGoodDetailVC alloc] init];
- detailVC.model = model;
-
- [self.navigationController pushViewController:detailVC animated:YES];
- }
- #pragma mark---保存本地
- -(void)saveLocal:(WKScriptMessage *)message
- {
- NSLog(@"%@",message.body);
- NSDictionary *dic =[KDPublicMethod dictionaryWithJsonString:message.body];
- [KDPublicMethod saveMessage:dic];
-
- }
- /**
- 传消息给js
- */
- - (void)sendmessageToJS:(WKScriptMessage *)message {
-
-
- NSDictionary *dict = [KDPublicMethod dictionaryWithJsonString:message.body];
- NSString *jsMethod = dict[@"js_callback"];
-
- NSDictionary *tokenPara = [KDPublicMethod getMessage];
- if (tokenPara.allKeys.count == 0) {
- return;
- }
- NSString *jsonDict = [KDPublicMethod convertToJsonData:tokenPara];
- NSString *callBacKMethod = [NSString stringWithFormat:@"%@('%@')",jsMethod,jsonDict];
- [self.webInterView evaluateJavaScript:callBacKMethod completionHandler:^(id _Nullable value, NSError * _Nullable error) {
-
- }];
-
- }
- /**
- 传token给js
- */
- - (void)sendUserTokenToJS:(WKScriptMessage *)message {
-
- __block NSString *token = [KDPAccountTool account].token;
- NSDictionary *dict = [KDPublicMethod dictionaryWithJsonString:message.body];
- NSString *jsMethod = dict[@"js_callback"];
- if (!token) {
- token = @"";
- }
- NSDictionary *tokenPara = @{@"token":token};
- NSString *jsonDict = [KDPublicMethod convertToJsonData:tokenPara];
- NSString *callBacKMethod = [NSString stringWithFormat:@"%@('%@')",jsMethod,jsonDict];
- [self.webInterView evaluateJavaScript:callBacKMethod completionHandler:^(id _Nullable value, NSError * _Nullable error) {
- }];
-
- }
- - (void)loadRequest {
- if (@available(iOS 9.0, *)) {
- NSArray * types=@[WKWebsiteDataTypeCookies,WKWebsiteDataTypeLocalStorage];
-
- NSSet *websiteDataTypes= [NSSet setWithArray:types];
- NSDate *dateFrom = [NSDate dateWithTimeIntervalSince1970:0];
-
- [[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:websiteDataTypes modifiedSince:dateFrom completionHandler:^{
-
- }];
- }
- // NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:self.url]];
- NSString *urlStr = [self.url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
- NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlStr]
- cachePolicy:NSURLRequestReloadIgnoringCacheData
- timeoutInterval:15.0];
- [self.webInterView loadRequest:theRequest];
- }
- - (void)viewWillAppear:(BOOL)animated {
- [super viewWillAppear:animated];
- self.tabBarController.tabBar.hidden=YES;
- self.navBar.navTitleLabel.textColor = [UIColor whiteColor];
- self.navBar.navTitleLabel.text=self.webInterView.title;
-
- }
- - (void)updateSelectorWithH5 {
-
- if (@available(iOS 9.0, *)) {
- NSArray * types=@[WKWebsiteDataTypeCookies,WKWebsiteDataTypeLocalStorage];
-
- NSSet *websiteDataTypes= [NSSet setWithArray:types];
- NSDate *dateFrom = [NSDate dateWithTimeIntervalSince1970:0];
-
- [[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:websiteDataTypes modifiedSince:dateFrom completionHandler:^{
-
- }];
- }
-
-
- NSString *callBacKMethod = [NSString stringWithFormat:@"%@()",refresh_h5];
- [self.webInterView evaluateJavaScript:callBacKMethod completionHandler:^(id _Nullable value, NSError * _Nullable error) {
-
- }];
- }
- /**
- kvo监听进度条
-
- @param keyPath keyPath description
- @param object object description
- @param change change description
- @param context context description
- */
- - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
- if ([keyPath isEqualToString:NSStringFromSelector(@selector(estimatedProgress))] && object == self.webInterView ) {
- [self.progressView setAlpha:1.0];
-
- [self.progressView setProgress:self.webInterView.estimatedProgress ];
- if (self.webInterView.estimatedProgress >= 1.0) {
- [UIView animateWithDuration:0.7 animations:^{
- [self.progressView setProgress:1.0 animated:YES];
- [self.progressView setAlpha:0.0];
-
- }];
-
- }
- }else{
- [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
- }
- }
- - (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
- self.navBar.navTitleLabel.text=self.webInterView.title;
- [[UIApplication sharedApplication]setNetworkActivityIndicatorVisible:NO];
- [self updateNavigationBarButtons];
- [self.webInterView.scrollView.mj_header endRefreshing];
- }
- #pragma mark- WKNavigationDelegate delegate
- /**
- 开始加载web的时候
-
- @param webView webView description
- @param navigation navigation description
- */
- - (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{
- //开始加载的时候,让进度条显示
- self.progressView.hidden = NO;
- self.progressView.progress = 0;
- self.progressView.alpha = 1.0;
- self.navBar.navTitleLabel.text=webView.title;
- [UIView animateWithDuration:0.8 animations:^{
- self.progressView.progress = 0.6;
-
- }];
- }
- -(void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
- {
- NSURL *url = navigationAction.request.URL;
- UIApplication *app = [UIApplication sharedApplication];
-
- // 打开appstore
- if ([url.absoluteString containsString:@"https://itunes.apple.com/cn/app/"])
- {
- if ([app canOpenURL:url])
- {
- //设备系统为IOS 10.0或者以上的
- if (@available(iOS 10.0, *)) {
- [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:nil];
- } else {
- [[UIApplication sharedApplication] openURL:url];
- }
-
- decisionHandler(WKNavigationActionPolicyCancel);
- return;
- }
- }
- decisionHandler(WKNavigationActionPolicyAllow);
-
-
-
- }
- - (WKWebView *)webInterView{
- if (!_webInterView) {
-
- WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
- config.allowsInlineMediaPlayback = NO;
-
- _webInterView = [[WKWebView alloc]initWithFrame:CGRectMake(0, KDNavBarHeight, SCREEN_WIDTH, SCREEN_HEIGHT-KDNavBarHeight-KDTabBottomHeight) configuration:config];
-
- //使用kvo监听进度
- [_webInterView addObserver:self forKeyPath:NSStringFromSelector(@selector(estimatedProgress)) options:0 context:nil];
- _webInterView.backgroundColor = [UIColor colorWithRed:240.0/255 green:240.0/255 blue:240.0/255 alpha:1.0];
-
- _webInterView.UIDelegate = self;
- //手势触摸滑动
- _webInterView.allowsBackForwardNavigationGestures = YES;
- //自适应
- [_webInterView sizeToFit];
-
-
- }
- return _webInterView;
- }
- #pragma mark-
- #pragma mark- SetupConstraints
- /** 加载配置以及视图添加*/
- - (void)loadSubViewsConfiguration{
-
- [self.view addSubview:self.webInterView];
- }
- - (UIButton *)returnBtn {
- if (!_returnBtn) {
- _returnBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
- [_returnBtn setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
-
- [_returnBtn addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
- }
- return _returnBtn;
- }
- - (UIButton *)closeButton {
- if (!_closeButton) {
-
- _closeButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
- [_closeButton setImage:[UIImage imageNamed:@"close_web"] forState:UIControlStateNormal];
- [_closeButton addTarget:self action:@selector(closeAction) forControlEvents:UIControlEventTouchUpInside];
- }
- return _closeButton;
- }
- - (UIButton *)refreshButton {
- if (!_refreshButton) {
- _refreshButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
- [_refreshButton setImage:[UIImage imageNamed:@"icon_web_refresh"] forState:UIControlStateNormal];
- [_refreshButton addTarget:self action:@selector(refreshAction) forControlEvents:UIControlEventTouchUpInside];
-
- _refreshButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
- }
- return _refreshButton;
- }
- - (void)backAction {
- NSArray *viewControllers = self.navigationController.viewControllers;
- if (viewControllers.count < 1){
- [self dismissViewControllerAnimated:YES completion:nil];
- }else {
- if (self.webInterView.canGoBack) {
- [self.webInterView goBack];
- }else{
- [self.navigationController popViewControllerAnimated:YES];
- }
- }
-
-
- }
- #pragma mark -----------
- - (void)updateNavigationBarButtons {
-
- }
- - (void)closeAction {
- [self.navigationController popViewControllerAnimated:YES];
- }
- - (void)refreshAction {
-
- [self.webInterView reload];
- }
- - (UIProgressView *)progressView{
- if (!_progressView) {
- _progressView = [[UIProgressView alloc]initWithProgressViewStyle:UIProgressViewStyleDefault];
- _progressView.frame = CGRectMake(0, KDNavBarHeight, self.view.frame.size.width, 2);
- //设置进度条的色彩
- [_progressView setTrackTintColor:[UIColor colorWithRed:240.0/255 green:240.0/255 blue:240.0/255 alpha:1.0]];
- _progressView.progressTintColor = [UIColor colorWithHexString:ThemeColor];
- }
- return _progressView;
- }
- //观察的移除
- - (void)dealloc{
- [self.webInterView removeObserver:self forKeyPath:NSStringFromSelector(@selector(estimatedProgress))];
- [[NSNotificationCenter defaultCenter] removeObserver:self];
- }
- @end
|