In apps that run in iOS 8 and later, use the WKWebView class instead of using UIWebView. Additionally, consider setting the WKPreferences property javaScriptEnabled to NO if you render files that are not supposed to run JavaScript.
这是Apple Library里UIWebView部分的note,也就是说从iOS8开始,建议使用WKWebView替代UIWebView,就像UIAlertViewController替代UIAlertView一样,这次正好要做一个H5的页面和APP进行交互,相比于UIWebView,WK的加载速度快了一倍,但占用的内存却少了,WK也新增了一些方法,使用起来更方便,下面就说说WKWebView的基本使用,来实现简单的web页面交互
上代码:
1、首先得引入库文件,WKWebView是WebKit的,#import <WebKit/WebKit.h>
2、声明属性:@property (strong,nonatomic) WKWebView *webView;
3、初始化: _webView = [[WKWebView alloc]initWithFrame:[UIScreen mainScreen].bounds];
4、说一说如何添加透明的网页,以前可能设置背景色为clearColor就可以,但是WK不行:_webView.backgroundColor = [UIColor clearColor];
_webView.opaque = NO;
5、设置代理,WK有两个代理WKUIDelegate,WKNavigationDelegate,交互涉及到的主要的第二个里面的代理方法,所以:_webView.navigationDelegate = self;
6、开始加载web内容:NSURLRequest *request =[NSURLRequest requestWithURL:[NSURL URLWithString:alertObj[@"h5"]]];
[_webView loadRequest:request];
7、加载完毕,显示网页
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
[[UIApplication sharedApplication].keyWindow addSubview:_webView];
}
接下里就是交互部分了
这里主要用到的是用户点击web页面的按钮,App拦截下来,在App端进行处理
当用户点击页面的按钮,会走 - (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler;这个代理函数,我们就在这里面进行拦截。
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
NSURL *responseUrl = navigationAction.request.URL;
NSString *urlStr = [responseUrl absoluteString];
if ([[responseUrl scheme] isEqualToString:baseUrlScheme]) {
if ([urlStr containsString:baseShareUrlPath]) {
//点击立即分享
[VPKCShare showShareWithPlatformImages:@[@"fx_pengyouquan"]];
decisionHandler(WKNavigationActionPolicyCancel);
} else if([responseUrl.path containsString:baseCloseUrlPath]){
//点击关闭
[_webView removeFromSuperview];
decisionHandler(WKNavigationActionPolicyCancel);
} else if([responseUrl.path containsString:baseGetUrlPath]){
//点击立即领取
decisionHandler(WKNavigationActionPolicyAllow);
} else {
decisionHandler(WKNavigationActionPolicyAllow);
}
} else {
decisionHandler(WKNavigationActionPolicyAllow);
}
}
就是将要跳转的url拿来进行比较,如果是我们要拦截的url,就执行decisionHandler(WKNavigationActionPolicyCancel);如果不是,就执行decisionHandler(WKNavigationActionPolicyAllow);就像UIWebView里的代理海曙返回YES和NO一样,这个是一定要写的,不然程序就会崩溃。
关于交互,还有两个类似的代理函数
1、收到服务器的response后调用 - (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler;
2、服务器redirect时调用 - (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(null_unspecified WKNavigation *)navigation;