iOS WKWebView UI增强(上拉刷新,JS交互,加载进度条)

iOS WKWebView UI增强(上拉刷新,JS交互,加载进度条)


需求:WKWebView的一些增加模块,例如上拉刷新,JS交互,加载进度条等等持续更新


阅读前提:

  • 了解WKWebView基本初始化及使用

GitHub地址(附代码) : iOS WKWebView UI增强

地址 : iOS WKWebView UI增强

博客地址 : iOS WKWebView UI增强

掘金地址 : iOS WKWebView UI增强


使用WKWebView需要在项目导入WebKit.framework以及Info.plist文件中添加权限

NSAppTransportSecurity
    
        NSAllowsArbitraryLoads
        
    

1. 与JS交互

如需与JS交互可在初始化时配置WKWebViewConfiguration对象,然后注册[[_webView configuration].userContentController addScriptMessageHandler:self name:@"getMessage"];

如上我们添加了一个名为getMessage的通知,例如,前端页面里有一个登陆按钮,前端小伙伴仅仅需要在登陆方法的最后加上如下代码即可在用户点击前端界面的登陆按钮时通知我们,注意getMessage两端必须一致!

try {
    window.webkit.messageHandlers.getMessage.postMessage(jsonStr)
} catch(error) {
    console.log(error)
}

然后我们即可通过该方法接收到前端页面上某次点击事件

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    log4cplus_info("XDX_LOG", "%s - %s receive the message name is %s, message content is %s.", ModuleName, __func__,[NSString stringWithFormat:@"%@",message.name].UTF8String, [NSString stringWithFormat:@"%@",message.body].UTF8String);
}

2. 上拉刷新

2-1 .如需上拉刷新功能,可直接使用MJRefresh,仅仅在初始化时如下配置即可,然后在didStartProvisionalNavigation开始加载网页时结束刷新即可。

    TVUMJRefreshNormalHeader *header = [TVUMJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerRefresh)];
    [header setTitle:@"Pull down to refresh" forState:TVUMJRefreshStateIdle];
    [header setTitle:@"Release to refresh" forState:TVUMJRefreshStatePulling];
    [header setTitle:@"Loading ..." forState:TVUMJRefreshStateRefreshing];
    header.lastUpdatedTimeLabel.hidden = YES;
    self.webView.scrollView.mj_header = header;
    
- (void)headerRefresh{
    // If user enter our app (not network), the URL is NULL even if we have already setted.
    if (!self.webView.URL) {
        log4cplus_error("XDX_LOG", "Refresh webview error, current URL is NULL !");
        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:self.yourWebAddress] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:XDX_URL_TIMEOUT];
        [self.webView loadRequest:request];
    }
    [self.webView reload];
}

- (void)endRefresh{
    [self.webView.scrollView.mj_header endRefreshing];
}

- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
    [self endRefresh];
}



2-2. 注意,因为WKWebview内部的UIScrollView与上滑手势冲突,所以我们还需要实现重写下面方法,该方法表示如果与前端页面手势冲突则双方都将执行

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(nonnull UIGestureRecognizer *)otherGestureRecognizer {
    return YES;
}

3. 进度条加载

3-1. 初始化UIProgressView

@property (nonatomic, strong) UIProgressView    *progressView;

    self.progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, 0, [[UIScreen mainScreen] bounds].size.width, 0.8)];
    self.progressView.progressTintColor = [UIColor greenColor];
    //设置进度条的高度,下面这句代码表示进度条的宽度变为原来的1倍,高度变为原来的1.5倍.
    self.progressView.transform = CGAffineTransformMakeScale(1.0f, 1.5f);
    [self.webView addSubview:self.progressView];
    

3-2. 当网页加载时显示ProgressView

- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
    [self endRefresh];
    
    if ([self.progressView isDescendantOfView:self.webView]) {
        self.progressView.hidden = NO;
        self.progressView.transform = CGAffineTransformMakeScale(1.0f, 1.5f);
    }
}

3-3. 为webView添加通知 [self.webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];

3-3. 在通知中检测是否加载完成时进度条消失

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if ([self.progressView isDescendantOfView:self.webView]) {
        if ([keyPath isEqualToString:@"estimatedProgress"]) {
            self.progressView.progress = self.webView.estimatedProgress;
            if (self.progressView.progress == 1) {
                /*
                 *添加一个简单的动画,将progressView的Height变为1.4倍,在开始加载网页的代理中会恢复为1.5倍
                 *动画时长0.25s,延时0.3s后开始动画
                 *动画结束后将progressView隐藏
                 */
                
                __weak ViewController *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 observeValueForKeyPath:keyPath ofObject:object change:change context:context];
        }
    }
}

你可能感兴趣的:(iOS WKWebView UI增强(上拉刷新,JS交互,加载进度条))