设为首页 加入收藏

TOP

iOS与H5交互(WKWbebView)(一)
2019-08-26 07:09:38 】 浏览:79
Tags:iOS 交互 WKWbebView

前言:

在iOS开发中,或多或少的会嵌入一些H5页面,有时候需要原生代码和H5页面进行交互。iOS8开始苹果推出性能更强大的WKWebView,所以一下方法是关于WKWebView与JS的交互。

创建WKWebView:

遵守协议

<WKNavigationDelegate, WKUIDelegate, WKScriptMessageHandler>

 

-(WKWebView *)wkwebview

{

    if (!_wkwebview) {

        _wkwebview = [[WKWebView alloc] initWithFrame:CGRectMake(0, HeightSignal, ScreenWidth, ScreenHeight-HeightSignal-HeightBottomSafe)];

        _wkwebview.scrollView.backgroundColor = [UIColor whiteColor];

        _wkwebview.navigationDelegate = self;

        _wkwebview.UIDelegate = self;

        [self.view addSubview:_wkwebview];

    }

    return _wkwebview;

}

顶部网页加载进度条:

self.progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, HeightSignal, [[UIScreen mainScreen] bounds].size.width, 2)];

    self.progressView.backgroundColor = [UIColor blueColor];

    //设置进度条的高度,下面这句代码表示进度条的宽度变为原来的1倍,高度变为原来的1.5倍.

    self.progressView.transform = CGAffineTransformMakeScale(1.0f, 1.5f);

    [self.view addSubview:self.progressView];

    [self.wkwebview addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];//进度监听

 

#pragma mark 加载进度监听

- (void)observeva lueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {

    if ([keyPath isEqualToString:@"estimatedProgress"]) {

        self.progressView.progress = self.wkwebview.estimatedProgress;

        if (self.progressView.progress == 1) {

            /*

             *添加一个简单的动画,将progressView的Height变为1.4倍,在开始加载网页的代理中会恢复为1.5倍

             *动画时长0.25s,延时0.3s后开始动画

             *动画结束后将progressView隐藏

             */

            __weak typeof (self)weakSelf = self;

            [UIView animateWithDuration:0.25f delay:0.3f options:UIViewAnimationOptionCurveEaseOut animations:^{

                weakSelf.progressView.transform = CGAffineTransformMakeScale(1.0f, 1.4f);

            } completion:^(BOOL finished) {

                weakSelf.progressView.hidden = YES;

                

            }];

        }

    }else{

        [super observeva lueForKeyPath:keyPath ofObject:object change:change context:context];

    }

}

 

添加JS事件监控:

 

-(void)viewWillAppear:(BOOL)animated

{

    [super viewWillAppear:animated];

    [self.wkwebview.configuration.userContentController addScriptMessageHandler:self name:@"share"];//分享

   

}

 

移除JS事件监控:

-(void)viewWillDisappear:(BOOL)animated

{

    [super viewWillDisappear:animated

首页 上一页 1 2 下一页 尾页 1/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇iOS代理模式(delegate)的使用 下一篇Unity 4.7 导出工程在XCode9/10上..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目