js与OC互相调用 —— WKWebView拦截Url
2017-11-13 本文已影响0人
杭州七木科技
首先介绍下WKWebview与UIWebview的区别,UIWebView
自iOS2就有,WKWebView
从iOS8才有,毫无疑问WKWebView
将逐步取代笨重的UIWebView
。通过简单的测试即可发现UIWebView
占用过多内存,且内存峰值更是夸张。WKWebView
网页加载速度也有提升,但是并不像内存那样提升那么多。下面列举一些其它的优势:
* 更多的支持HTML5的特性
* 官方宣称的高达60fps的滚动刷新率以及内置手势
* Safari相同的JavaScript引擎
* 将UIWebViewDelegate与UIWebView拆分成了14类与3个协议([官方文档说明](https://developer.apple.com/library/mac/documentation/Cocoa/Reference/WebKit/ObjC_classic/index.html))
* 另外用的比较多的,增加加载进度属性:`estimatedProgress`
1.加载本地的Html文件,具体文件见上一篇文章附图
2.创建WKWebView
- (void)initWKWebView
{
WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
configuration.userContentController = [WKUserContentController new];
WKPreferences *preferences = [WKPreferences new];
preferences.javaScriptCanOpenWindowsAutomatically = YES;
preferences.minimumFontSize = 30.0;
configuration.preferences = preferences;
self.webView = [[WKWebView alloc] initWithFrame:self.view.frame configuration:configuration];
NSString *urlStr = [[NSBundle mainBundle] pathForResource:@"index.html" ofType:nil];
NSURL *fileURL = [NSURL fileURLWithPath:urlStr];
[self.webView loadFileURL:fileURL allowingReadAccessToURL:fileURL];
self.webView.navigationDelegate = self;
self.webView.UIDelegate = self;
[self.view addSubview:self.webView];
}
附属相关操作,创建进度条,监听estimatedProgress属性
CGFloat kScreenWidth = [[UIScreen mainScreen] bounds].size.width;
UIProgressView *progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 2)];
progressView.tintColor = [UIColor redColor];
progressView.trackTintColor = [UIColor lightGrayColor];
[self.view addSubview:progressView];
self.progressView = progressView;
[self.webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil]; // 监听网页加载进度
3.实现WKNavigationDelegate代理方法拦截Url
使用WKNavigationDelegate中的代理方法,拦截自定义的URL来实现JS调用OC方法
#pragma mark - WKNavigationDelegate
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
{
NSURL *URL = navigationAction.request.URL;
NSString *scheme = [URL scheme];
if ([scheme isEqualToString:@"haleyaction"]) {
[self handleCustomAction:URL];
decisionHandler(WKNavigationActionPolicyCancel);
return;
}
decisionHandler(WKNavigationActionPolicyAllow);
}
注意事项
1.如果实现了这个代理方法,就必须得调用decisionHandler这个block,否则会导致app 崩溃。block参数是个枚举类型,WKNavigationActionPolicyCancel代表取消加载,相当于UIWebView的代理方法return NO的情况;WKNavigationActionPolicyAllow代表允许加载,相当于UIWebView的代理方法中 return YES的情况。
方法区分,设置,和上一篇文章一样
#pragma mark - private method
- (void)handleCustomAction:(NSURL *)URL
{
NSString *host = [URL host];
if ([host isEqualToString:@"scanClick"]) {
NSLog(@"扫一扫");
} else if ([host isEqualToString:@"shareClick"]) {
[self share:URL];
} else if ([host isEqualToString:@"getLocation"]) {
[self getLocation];
} else if ([host isEqualToString:@"setColor"]) {
[self changeBGColor:URL];
} else if ([host isEqualToString:@"payAction"]) {
[self payAction:URL];
} else if ([host isEqualToString:@"shake"]) {
[self shakeAction];
} else if ([host isEqualToString:@"goBack"]) {
[self goBack];
}
}
调用JS方法,WKWebView 提供了一个新的方法evaluateJavaScript:completionHandler:,实现OC 调用JS 等场景。
// 将结果返回给js
NSString *jsStr = [NSString stringWithFormat:@"setLocation('%@')",@"广东省深圳市南山区学府路XXXX号"];
[self.webView evaluateJavaScript:jsStr completionHandler:^(id _Nullable result, NSError * _Nullable error) {
NSLog(@"%@----%@",result, error);
}];
附属监听estimatedProgress,在代理方法中实现
// 计算wkWebView进度条
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
if (object == self.webView && [keyPath isEqualToString:@"estimatedProgress"]) {
CGFloat newprogress = [[change objectForKey:NSKeyValueChangeNewKey] doubleValue];
if (newprogress == 1) {
[self.progressView setProgress:1.0 animated:YES];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.7 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
self.progressView.hidden = YES;
[self.progressView setProgress:0 animated:NO];
});
}else {
self.progressView.hidden = NO;
[self.progressView setProgress:newprogress animated:YES];
}
}
}
// 释放时移除监听
- (void)dealloc
{
NSLog(@"dealloc ---%s",__FUNCTION__);
[self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
}
4.WKWebView中使用弹窗
在WKWebView中使用alert、confirm 等弹窗,就得实现WKWebView的WKUIDelegate中相应的代理方法。
例如,我在JS中要显示alert 弹窗,就必须实现如下代理方法,否则alert 并不会弹出。
#pragma mark - WKUIDelegate
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler
{
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提醒" message:message preferredStyle:UIAlertControllerStyleAlert];
[alert addAction:[UIAlertAction actionWithTitle:@"知道了" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
completionHandler();
}]];
[self presentViewController:alert animated:YES completion:nil];
}
html编写和相关方法调用区分,和上一篇文章大致相同,不多叙述。
以上文章实现了在WKWebview中实现JS和OC交互,并且使用了WKWebview中的estimatedProgress新属性,使用KVO监听,实现了基本的进度条功能。