注意点: WKWebView只支持iOS8以上且不支持xib,切勿使用xib进行拖拽
WKWebview 优势:
1.更多的支持HTML5的特性
2.官方宣称的高达60fps的滚动刷新率以及内置手势
3.将UIWebViewDelegate与UIWebView拆分成了14类与3个协议,以前很多不方便实现的功能得以实现。文档
4.Safari相同的JavaScript引擎
5.占用更少的内存
基本使用方法:
WKWebView有两个delegate,WKUIDelegate和WKNavigationDelegate。WKNavigationDelegate主要处理一些跳转、加载处理操作,WKUIDelegate主要处理JS脚本,确认框,警告框等。
#import <WebKit/WebKit.h>
@interface ZebWebViewController()<WKNavigationDelegate,WKUIDelegate,WKScriptMessageHandler>
@property (nonatomic, strong) UIProgressView *progressView;
@property (nonatomic,strong) WKWebView *wkwebView;
@end
@implementation ZebWebViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self SetUI];
}
-(void)SetUI{
[self setWKWebView];
[self setUIProgressView];
}
#pragma mark webview初始化
-(void)setWKWebView{
WKWebViewConfiguration *config=[[WKWebViewConfiguration alloc]init];
// 不开有视频就不能播放
config.allowsInlineMediaPlayback=YES;
config.preferences=[[WKPreferences alloc]init];
// 最小字体为10号
config.preferences.minimumFontSize = 10;
config.preferences.javaScriptEnabled = YES;
// 默认是不能通过JS自动打开窗口的,必须通过用户交互才能打开
config.preferences.javaScriptCanOpenWindowsAutomatically =YES;
// 通过js与webview内容交互配置
config.userContentController=[[WKUserContentController alloc]init];
// 添加一个名称,在JS通过这个名称发送消息
[config.userContentController addScriptMessageHandler:self name:@"GetTKL"];
self.wkwebView = [[WKWebView alloc] initWithFrame:self.webviewSupView.bounds configuration:config];
self.wkwebView.navigationDelegate=self;
self.wkwebView.UIDelegate=self;
//允许右滑返回上个链接,左滑前进
self.wkwebView.allowsBackForwardNavigationGestures = YES;
//允许链接3D Touch
self.wkwebView.allowsLinkPreview = YES;
[self.wkwebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:[ZebUserInfo sharedInstance].userShoppingMallUrl]]];
[self.webviewSupView addSubview:self.wkwebView];
[self.wkwebView mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.mas_equalTo(0);
make.top.mas_equalTo(0);
make.right.mas_equalTo(0);
make.bottom.mas_equalTo(0);
}];
}
#pragma mark UIProgressView初始化
-(void)setUIProgressView{
//进度条初始化
self.progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, 0, KDeviceWidth, 2)];
self.progressView.backgroundColor = [UIColor whiteColor];
self.progressView.progressTintColor = [FSColor mainColor];
self.progressView.trackTintColor = [UIColor clearColor];
//设置进度条的高度,下面这句代码表示进度条的宽度变为原来的1倍,高度变为原来的1.5倍.
self.progressView.transform = CGAffineTransformMakeScale(1.0f, 1.5f);
[self.webviewSupView addSubview:self.progressView];
@weakify(self)
[RACObserve(self.wkwebView, estimatedProgress) subscribeNext:^(id x) {
self_weak_.progressView.progress = self_weak_.wkwebView.estimatedProgress;
if (self_weak_.progressView.progress == 1) {
/*
*添加一个简单的动画,将progressView的Height变为1.4倍,在开始加载网页的代理中会恢复为1.5倍
*动画时长0.25s,延时0.3s后开始动画
*动画结束后将progressView隐藏
*/
[UIView animateWithDuration:0.25f delay:0.3f options:UIViewAnimationOptionCurveEaseOut animations:^{
self_weak_.progressView.transform = CGAffineTransformMakeScale(1.0f, 1.4f);
} completion:^(BOOL finished) {
self_weak_.progressView.hidden = YES;
}];
}}];
}
#pragma mark 代理
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
//此处可以得到之前配置项注入的名称,并且可以携带数据,json对象或者json字串等~
if ([message.name isEqualToString:@"GetTKL"]) {
NSDictionary *dict=message.body;
NSArray *Arr=dict[@"data"];
ZEBLog(@"js调用oc---------begin--------");
if (Arr.count>0) {
dispatch_sync(dispatch_get_main_queue(), ^{
[MBProgressHUD showSuccess:@"复制成功!"];
});
}
[ZebUserInfo sharedInstance].shareDocument=[NSString stringWithFormat:@"%@",Arr[0]];
UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
pasteboard.string = [ZebUserInfo sharedInstance].shareDocument;
ZEBLog(@"js调用oc---------The End-------");
}
}
//在发送请求之前,决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
ZEBLog(@"在发送请求之前,决定是否跳转:%@",navigationAction.request.URL);
self.currentURL = webView.URL.absoluteString;
decisionHandler(WKNavigationActionPolicyAllow);
}
//开始加载
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
ZEBLog(@"开始加载网页");
//开始加载网页时展示出progressView
self.progressView.hidden = NO;
//开始加载网页的时候将progressView的Height恢复为1.5倍
self.progressView.transform = CGAffineTransformMakeScale(1.0f, 1.5f);
//防止progressView被网页挡住
[self.view bringSubviewToFront:self.progressView];
}
//在收到响应后,决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler {
ZEBLog(@"在收到响应后,决定是否跳转");
decisionHandler(WKNavigationResponsePolicyAllow);
}
// 当内容开始返回时调用
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation {
ZEBLog(@"内容开始返回");
}
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
ZEBLog(@"加载完成");
//加载完成后隐藏progressView
self.progressView.hidden = YES;
}
//加载失败
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error {
ZEBLog(@"加载失败");
//加载失败同样需要隐藏progressView
self.progressView.hidden = YES;
}
//接收到服务器跳转请求之后调用
- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation {
ZEBLog(@"接收到服务器跳转请求之后调用");
}
- (void)dealloc {
// VC销毁时,移除交互对象
[self.wkwebView.configuration.userContentController removeScriptMessageHandlerForName:@"GetTKL"];
}
@end