iOS8以后,苹果推出了新框架Wekkit,提供了替换UIWebView的组件WKWebView。各种UIWebView的问题没有了,速度更快了,占用内存少了,一句话,WKWebView是App内部加载网页的最佳选择! 下面我们来看下WKWebView的特性: 在性能、稳定性、功能方面有很大提升(最直观的体现就是加载网页是占用的内存,模拟器加载百度与开源中国网站时,WKWebView占用23M,而UIWebView占用85M); 允许JavaScript的Nitro库加载并使用(UIWebView中限制); 支持了更多的HTML5特性; 高达60fps的滚动刷新率以及内置手势; 将UIWebViewDelegate与UIWebView重构成了14类与3个协议(查看苹果官方文档); 然后从以下几个方面说下WKWebView的基本用法: 加载网页 加载的状态回调 新的WKUIDelegate协议 动态加载并运行JS代码 webView 执行JS代码 JS调用App注册过的方法 以上对WKWebView的描述文字是我从某网站上摘抄的。 网上我也找过很多WKWebView的讲解,但是有关WKWebView的功能讲的不是很全面,尤其是JS交互这里更是不够详细,那么,下面我就来给大家详细讲解一下WKWebView的基本属性以及JS交互: 1、根据生成的WKUserScript对象,初始化WKWebViewConfiguration//根据生成的WKUserScript对象,初始化WKWebViewConfigurationconfig=[WKWebViewConfiguration new]; [config.userContentController addScriptMessageHandler:self name:@"iosApp"];1232、WKWebView的创建(与UIWebView创建基本一样)//初始化WKWebViewself.dzWebView=[[WKWebView alloc]initWithFrame:CGRectMake(0,64+10,self.view.frame.size.width,self.view.frame.size.height-64-35-10) configuration:config]; self.dzWebView.navigationDelegate=self; self.dzWebView.UIDelegate=self; [self.view addSubview:self.dzWebView]; NSString *path =[[NSBundle mainBundle] pathForResource:@"dzzJs交互(iOS)" ofType:@"html"]; NSString *htmlStr=[NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil]; [self.dzWebView loadHTMLString:htmlStr baseURL:[NSURL URLWithString:path]];123456783、添加KVO监听// 添加KVO监听 [self.dzWebView addObserver:self forKeyPath:@"loading" options:NSKeyValueObservingOptionNew context:nil]; [self.dzWebView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:nil]; [self.dzWebView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];123456789101112134、添加进度条// 添加进入条 self.progressView = [[UIProgressView alloc] init]; self.progressView.frame = CGRectMake(0,64, 320, 10); [self.view addSubview:self.progressView]; self.progressView.backgroundColor = [UIColor redColor];123455、kvo监听#pragma mark - KVO-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary*)change context:(void *)context{
if ([keyPath isEqualToString:@"loading"]) {
NSLog(@"loading");
} else if ([keyPath isEqualToString:@"title"]) {
self.title = self.dzWebView.title;
} else if ([keyPath isEqualToString:@"estimatedProgress"]) {
self.progressView.progress = self.dzWebView.estimatedProgress;
}
// 加载完成
if (!self.dzWebView.loading) {
[UIView animateWithDuration:0.5 animations:^{
self.progressView.alpha = 0;
}];
}
}
6、获取JS交互内容(H5传给原生界面)
//获取js传给iOS的参数
-(void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
NSDictionary *dict=message.body;
NSLog(@">>%@",dict);
UIAlertController *alertController=[UIAlertController alertControllerWithTitle:[NSString stringWithFormat:@"%@",dict] message:nil preferredStyle:UIAlertControllerStyleAlert];
[alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
}]];
[self presentViewController:alertController animated:YES completion:^{}];
}
7、WKWebView基本属性
//关闭页面
[self.navigationController popViewControllerAnimated:YES];
// 后退
// 判断是否可以后退
if (self.dzWebView.canGoBack) {
[self.dzWebView goBack];
}
// 前进
// 判断是否可以前进
if (self.dzWebView.canGoForward) {
[self.dzWebView goForward];
}
//刷新
//这个是带缓存的验证
// [self.dzWebView reloadFromOrigin];
// 是不带缓存的验证,刷新当前页面
[self.dzWebView reload];
//停止载入
[self.dzWebView stopLoading];
//返回指定页面
if (self.dzWebView.backForwardList.backList.count >1) {
[self.dzWebView goToBackForwardListItem:self.dzWebView.backForwardList.backList[1]];
}
8、JS交互(原生页面调用H5方法)
//js方法名+参数
NSString* jsCode = @"executeJS()";
[self.dzWebView evaluateJavaScript:jsCode completionHandler:^(id object, NSError * error) {
NSLog(@"111111111");
}];
9、WKWebView的代理方法
#pragma mark WKNavigationDelegate
//类似UIWebView的-webViewDidStartLoad:页面开始加载时调用
-(void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{
[UIApplication sharedApplication].networkActivityIndicatorVisible=YES;
}
//类似UIWebView的-webViewDidFinishLoad:页面加载完成时调用
-(void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
}
//类似UIWebView的-webView:didFailLoadWithError:页面加载失败时调用
-(void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error{
NSLog(@"%@",error);
}
// 当内容开始返回时调用
-(void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation{
}
//类似UIWebView的-webView:shouldStartLoadWithRequest:navigationType:在发送请求之前,决定是否跳转
-(void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
// NSLog(@"%@",navigationAction.request);
// NSString *url=[navigationAction.request.URL.absoluteString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
// NSLog(@">>>>%@",url);
self.progressView.alpha = 1.0;
decisionHandler(WKNavigationActionPolicyAllow);
}
//接收到服务器跳转请求之后调用
- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation{
}
// 在收到响应后,决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler{
decisionHandler(WKNavigationResponsePolicyAllow);
}
#pragma mark WKUIDelegate
/*以下三个代理方法全都是与界面弹出提示框相关的(H5自带的这三张弹出框早iOS中不能使用,需要通过以下三种方法来实现),针对于web界面的三种提示框(警告框、确认框、输入框)分别对应三种代理方法*/
-(void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler{
//js里面的alert实现,如果不实现,网页的alert函数无效
UIAlertController *alertController=[UIAlertController alertControllerWithTitle:message message:nil preferredStyle:UIAlertControllerStyleAlert];
[alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
completionHandler();
}]];
[self presentViewController:alertController animated:YES completion:^{}];
}
- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL))completionHandler {
// js 里面的alert实现,如果不实现,网页的alert函数无效 ,
UIAlertController *alertController=[UIAlertController alertControllerWithTitle:message message:nil preferredStyle:UIAlertControllerStyleAlert];
[alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
completionHandler(YES);
}]];
[alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
completionHandler(NO);
}]];
[self presentViewController:alertController animated:YES completion:^{}];
}
-(void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * _Nullable))completionHandler{
//js里的输入框实现,如果不实现,网页的输入框无效
completionHandler(@"Client Not handler");
}