我们做项目的时候会避免不了使用WebView之类的滚动视图,之前一直在使用UIWebView。但UIWebView存在加载速度慢、占用内存大等问题,后来苹果在iOS8.0之后推出了WKWebView,增加了更多强大的功能,提供了丰富的接口。
1).下面主要说一下在使用WKWebView实现oc与js之间相互传值的功能实现:
首先引入<WebKit/WebKit.h>框架
#import <WebKit/WebKit.h>
下面是我要演示的html中需要调用的js代码
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf8">
<script language="javascript">
//1.返回
function backClick() {
window.webkit.messageHandlers.Back.postMessage(null);
}
//2.修改背景色
function colorClick() {
window.webkit.messageHandlers.Color.postMessage(null);
}
//3.js传参数
function paramClick() {
var content = document.getElementById("firstid").value;
window.webkit.messageHandlers.Param.postMessage({first:'来自js的数据:',second:content});
}
//展示oc所传js数据
function transferPrama(str) {
asyncAlert(str);//响应WKUIDelegate的代理方法runJavaScriptAlertPanelWithMessage
document.getElementById("secondid").value = str;
}
function asyncAlert(content) {
setTimeout(function() {
alert(content);
},1);
}
</script>
</head>
然后新建webView,配置参数和属性
- (WKWebView *)webView {
if (!_webView) {
//配置控制器
WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
configuration.userContentController = [WKUserContentController new];
//配置js调用统一参数
[configuration.userContentController addScriptMessageHandler:self name:@"Back"];
[configuration.userContentController addScriptMessageHandler:self name:@"Color"];
[configuration.userContentController addScriptMessageHandler:self name:@"Param"];
WKPreferences *preferences = [WKPreferences new];
preferences.javaScriptCanOpenWindowsAutomatically = YES;
preferences.minimumFontSize = 40.0;
configuration.preferences = preferences;
_webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, K_ScreenWidth, K_ScreenWidth*5/4-20) configuration:configuration];
_webView.UIDelegate = self;
NSString * urlStr = [[NSBundle mainBundle] pathForResource:@"wkwebview.html" ofType:nil];
NSURL * fileURL = [NSURL fileURLWithPath:urlStr];
[_webView loadFileURL:fileURL allowingReadAccessToURL:fileURL];
}
return _webView;
}
其中以下三个参数的配置是和js代码中的函数调用相对应的
//配置js调用统一参数
[configuration.userContentController addScriptMessageHandler:self name:@"Back"];
[configuration.userContentController addScriptMessageHandler:self name:@"Color"];
[configuration.userContentController addScriptMessageHandler:self name:@"Param"];
添加代理WKUIDelegate和WKScriptMessageHandler
<WKUIDelegate,WKScriptMessageHandler>
实现对应代理方法
WKUIDelegate代理方法:
#pragma mark - WKUIDelegate
// 在JS端调用alert函数alert(content)时,会触发此代理方法,通过message可以拿到JS端所传的数据,在iOS端得到结果后,需要回调JS,通过completionHandler回调给JS端
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler {
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"JS调用alert" message:message preferredStyle:UIAlertControllerStyleAlert];
[alert addAction:[UIAlertAction actionWithTitle:@"知道了" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
completionHandler();
}]];
[self presentViewController:alert animated:YES completion:nil];
}
// JS端调用confirm函数时,会触发此方法,通过message可以拿到JS端所传的数据,在iOS端显示原生alert得到YES/NO后,通过completionHandler回调给JS端
- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL result))completionHandler {
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"confirm" message:@"JS调用confirm" preferredStyle:UIAlertControllerStyleAlert];
[alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
completionHandler(YES);
}]];
[alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
completionHandler(NO);
}]];
[self presentViewController:alert animated:YES completion:NULL];
}
//JS端调用prompt函数时,会触发此方法,要求输入一段文本,在原生输入得到文本内容后,通过completionHandler回调给JS
- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(nullable NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * __nullable result))completionHandler {
NSLog(@"%s", __FUNCTION__);
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"textinput" message:@"JS调用输入框" preferredStyle:UIAlertControllerStyleAlert];
[alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
textField.textColor = [UIColor redColor];
}];
[alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
completionHandler([[alert.textFields lastObject] text]);
}]];
[self presentViewController:alert animated:YES completion:NULL];
}
以上三个代理方法分别会在JS端调用alert函数、confirm函数以及prompt函数时,分别触发对应的方法。
WKScriptMessageHandler代理方法:
#pragma mark - WKScriptMessageHandler
//接收从js传给oc的数据
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
if ([message.name isEqualToString:@"Back"]) {
[self.navigationController popViewControllerAnimated:YES];
} else if ([message.name isEqualToString:@"Color"]) {
[self changeBackGroundViewColor];
} else if ([message.name isEqualToString:@"Param"]) {
[self jsParams:message.body];
}
}
上面代理方法是用来接收从js传给oc的数据,其中(WKScriptMessage *)message 的name属性用于对应在js代码中设置的参数,body是接收的传过来的数据。
//oc数据传给js
- (void)transterClick {
NSString * paramString = self.OCView.fieldView.text;
//transferPrama()是JS的语言
NSString * jsStr = [NSString stringWithFormat:@"transferPrama('%@')",paramString];
[self.webView evaluateJavaScript:jsStr completionHandler:^(id _Nullable result, NSError * _Nullable error) {
NSLog(@"result=%@ error=%@",result, error);
}];
}
上面方法是用来将oc数据传给js,其中transferPrama()是js的语言,是js代码中用来接受oc数据的方法,其中参数str是oc传过去的数据,js接收方法如下:
//展示oc所传js数据
function transferPrama(str) {
document.getElementById("secondid").value = str;
}
2).下面说一下WKWebView的WKNavigationDelegate代理方法:
在上面的基础上添加代理WKNavigationDelegate
<WKNavigationDelegate>
设置代理:
_webView.navigationDelegate = self;
对应代理方法
WKUIDelegate代理方法:
#pragma mark - WKNavigationDelegate
/**
//如果不实现这个方法,web视图将加载请求,或在适当的情况下,其转发到另一个应用程序。(在发送请求之前,决定是否跳转)
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
NSString *hostname = navigationAction.request.URL.host.lowercaseString;
if (navigationAction.navigationType == WKNavigationTypeLinkActivated
&& ![hostname containsString:@".baidu.com"]) {
// 对于跨域,需要手动跳转
[[UIApplication sharedApplication] openURL:navigationAction.request.URL];
// 不允许web内跳转
decisionHandler(WKNavigationActionPolicyCancel);
} else {
self.progressView.alpha = 1.0;
decisionHandler(WKNavigationActionPolicyAllow);
}
NSLog(@"%s", __FUNCTION__);
}
*/
/**
//如果不实现这个方法,将允许响应web视图,如果web视图可以表现出来。(在收到响应后,决定是否跳转)
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler {
// 如果响应的地址是百度,则允许跳转
if ([navigationResponse.response.URL.host.lowercaseString isEqual:@"www.baidu.com"]) {
// 允许跳转
decisionHandler(WKNavigationResponsePolicyAllow);
return;
}
// 不允许跳转
decisionHandler(WKNavigationResponsePolicyCancel);
}
*/
//开始调用一个主框架导航(页面开始加载时调用)
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(null_unspecified WKNavigation *)navigation {
}
//调用的主要服务器接收到重定向框架(接收到服务器跳转请求之后调用)
- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(null_unspecified WKNavigation *)navigation {
}
//开始加载数据时出现错误时调用(加载失败时调用)
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error {
}
//内容开始到达时调用的主要框架(当内容开始返回时调用)
- (void)webView:(WKWebView *)webView didCommitNavigation:(null_unspecified WKNavigation *)navigation {
}
//主框架导航完成时调用(页面加载完成之后调用)
- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation {
}
//发生错误时调用(导航失败时会回调)
- (void)webView:(WKWebView *)webView didFailNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error {
}
/**
//讨论如果你不实现这个方法,web视图将响应身份验证的挑战,对于HTTPS的都会触发此代理,如果不要求验证,传默认就行,如果需要证书验证,与使用AFN进行HTTPS证书验证是一样的
- (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * _Nullable credential))completionHandler {
completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil);
}
*/
//调用web视图的web内容过程终止时调用,9.0才能使用
- (void)webViewWebContentProcessDidTerminate:(WKWebView *)webView API_AVAILABLE(macosx(10.11), ios(9.0)) {
}
设置WKWebView加载进度条:
添加属性:
@property(nonatomic,strong)UIProgressView * progressView;
创建UIProgressView:
- (UIProgressView *)progressView {
if (!_progressView) {
_progressView = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleBar];
_progressView.frame = CGRectMake(0, 0, K_ScreenWidth, 2.5);
_progressView.tintColor = [UIColor blueColor];
_progressView.trackTintColor = [UIColor lightGrayColor];
}
return _progressView;
}
_webView添加监听(记得退出时销毁):
#define k_estimatedProgress @"estimatedProgress"
[_webView addObserver:self forKeyPath:k_estimatedProgress options:NSKeyValueObservingOptionNew context:nil];
实现监听方法:
#pragma mark - KVO
//计算WKWebView进度条
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
if (object == self.webView && [keyPath isEqualToString:k_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];
}
}
}
Demo地址:WKWebView与js交互及代理方法
「欢迎指正交流」0_0