使用WKWebView需要在项目导入WebKit.framework以及Info.plist文件中添加权限
<key>NSAppTransportSecurity</key>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
复制代码
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];
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<NSString *,id> *)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];
复制代码
-
36.7w
-
程序员老鱼
掘金·日新计划
ChatGPT
OpenAI
-
12.1w
-
华为云开发者联盟
JavaScript