Starting in iOS 8.0 and OS X 10.10, use WKWebView to add web content to your app. Do not use UIWebView or WebView.
WKWebView新特性
- 占用内存变少了(模拟器加载百度首页,WKWebView占用22M,UIWebView占用65M)
- 更多的支持HTML5的特性
- 官方宣称高达60fps的滚动刷新率以及内置手势
- 和Safari相同的JavaScript引擎
WKWebView生命周期和跳转代理
#pragma mark - WKNavigationDelegate
// 页面开始加载时调用
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{
NSLog(@"页面开始加载:%s",__FUNCTION__);
}
// 当内容开始返回时调用
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation{
NSLog(@"内容开始返回:%s",__FUNCTION__);
}
// 页面加载完成之后调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
NSLog(@"页面加载完成:%s",__FUNCTION__);
}
// 页面加载失败时调用
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error {
NSLog(@"%@",error.debugDescription);
}
// 接收到服务器跳转请求之后调用
- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation{
}
// 在收到响应后,决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler{
NSLog(@"%@",navigationResponse.response.URL.absoluteString);
//允许跳转
decisionHandler(WKNavigationResponsePolicyAllow);
//不允许跳转
//decisionHandler(WKNavigationResponsePolicyCancel);
}
// 在发送请求之前,决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
NSLog(@"%@",navigationAction.request.URL.absoluteString);
//允许跳转
decisionHandler(WKNavigationActionPolicyAllow);
//不允许跳转
//decisionHandler(WKNavigationActionPolicyCancel);
}
前进 后退 刷新 进度条
//前进
webView.goBack()
//后退
webView.goForward()
//刷新
let request = NSURLRequest(URL:webView.URL!)
webView.loadRequest(request)
//监听是否可以前进后退,修改btn.enable属性
webView.addObserver(self, forKeyPath: "loading", options: .New, context: nil)
//监听加载进度
webView.addObserver(self, forKeyPath: "estimatedProgress", options: .New, context: nil)
//重写self的kvo方法
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer) {
if (keyPath == "loading") {
gobackBtn.enabled = webView.canGoBack
forwardBtn.enabled = webView.canGoForward
}
if (keyPath == "estimatedProgress") {
//progress是UIProgressView
progress.hidden = webView.estimatedProgress==1
progress.setProgress(Float(webView.estimatedProgress), animated: true)
}
}
JS中alert拦截
在WKWebview中,js的alert是不会出现任何内容的,你必须重写WKUIDelegate委托的runJavaScriptAlertPanelWithMessage message方法,自己处理alert。类似的还有Confirm和prompt,这里我只以alert为例。
// 输入框
- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(nullable NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * __nullable result))completionHandler{
completionHandler(@"hello");
}
// 确认框
- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL result))completionHandler{
completionHandler(YES);
}
// 警告框
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler {
UIAlertController *alert = [UIAlertController alertControllerWithTitle:webView.title message:message preferredStyle:UIAlertControllerStyleAlert];
[alert addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
completionHandler();
}]];
[self presentViewController:alert animated:YES completion:nil];
}
app调用js方法
WKWebView调用js方法和UIWebView类似,一个是evaluateJavaScript,一个是stringByEvaluatingJavaScriptFromString。获取返回值的方式不同,WKWebView用的是回调函数获取返回值。
//直接调用js
webView.evaluateJavaScript("hello()", completionHandler: nil)
//调用js带参数
webView.evaluateJavaScript("hello('ls')", completionHandler: nil)
//调用js获取返回值
webView.evaluateJavaScript("getName()") { (any,error) -> Void in
NSLog("%@", any as! String)
}
js调用app方法
1:注册handler需要在webView初始化之前;
//配置环境
WKWebViewConfiguration *conf = [[WKWebViewConfiguration alloc] init];
userContentController = [[WKUserContentController alloc] init];
conf.userContentController = userContentController;
// 注册方法
[userContentController addScriptMessageHandler:self name:@"webViewHandle"];
// 初始化
self.webView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:conf];
2:处理handler委托。ViewController实现WKScriptMessageHandler委托的方法
// 使用safari模拟器调试
// 前端需要用 window.webkit.messageHandlers.注册的方法名.postMessage({body:传输的数据} 来给native发送消息
// window.webkit.messageHandlers.webViewHandle.postMessage("Hello WebKit!")
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
NSLog(@"%@ -- %@",message.name, message.body);
}
3:通过 window.webkit.messageHandlers.webViewApp找到之前注册的handler对象,然后调用postMessage方法把数据传到app,app通过上一步的方法从message.body中解析方法名和参数
// 只能传一个参数 可以用json或字典组装参数,在app里去解析
var message = 'Hello WebKit!'
window.webkit.messageHandlers.webViewApp.postMessage(message);
参考文章
这里仅仅简要记录了基本用法。
- iOS 8 WebKit框架概览(上)译文
- iOS 8 WebKit框架概览(下)译文