iOS-WebKit之WKWebView(一个高性能的WebView)

   iOS 8.0之后,苹果退出全新的WebKit库,其中WKWebView控件的新特性与使用方法,它很好的解决了UIWebView存在的内存、加载速度等诸多问题。

一、WKWebView新特性

1、在性能、稳定性、功能方面有很大提升(最直观的体现就是加载网页是占用的内存,模拟器加载百度与开源中国网站时,WKWebView占用23M,而UIWebView占用85M);
2、允许JavaScript的Nitro库加载并使用(UIWebView中限制);
3、支持了更多的HTML5特性;
4、高达60fps的滚动刷新率以及内置手势;
5、重点内容将UIWebViewDelegate与UIWebView重构成了14类与3个协议(查看苹果官方文档);

实例:
iOS-WebKit之WKWebView(一个高性能的WebView)_第1张图片

二、具体实现步骤

//1、导入WebKit框架
#import <WebKit/WebKit.h>
//接收代理
@interface ViewController ()<WKNavigationDelegate,WKUIDelegate>
//2、创建属性
@property(nonatomic,strong)WKWebView *webView;
@end
- (void)viewDidLoad {
    [super viewDidLoad];
    //3、初始化WKWebView
    self.webView = [[WKWebView alloc]initWithFrame:self.view.bounds];
    //4、让webView请求数据
    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.tmall.com"]]];
    //5、接收代理
    _webView.UIDelegate = self;
    _webView.navigationDelegate = self;
    //6、加到视图上
    [self.view addSubview:self.webView];

}
//7、实现相应的代理方法
#pragma mark - WKNavigationDelegate
/* 页面开始加载的时候调用 */
-(void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{
    NSLog(@"页面开始加载");
}


/* 当内容开始返回时调用 */
-(void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation{
    NSLog(@"内容开始返回的时候");
}

/* 页面加载完成后调用 */
-(void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
    NSLog(@"页面加载完成");
}

/* 页面加载失败时调用 */
-(void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error{
    NSLog(@"页面加载失败");
}


/* 接收到服务器跳转请求之后调用 */
-(void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation{
    NSLog(@"接收到服务器跳转请求之后调用");
}

/* 在收到响应后,决定是否跳转 */
-(void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler{
    //如果相应的网址是天猫,则允许跳转
    if ([navigationResponse.response.URL.host.lowercaseString isEqualToString:@"www.tmall.com"]) {
        //允许跳转
        decisionHandler(WKNavigationResponsePolicyAllow);
        return;
    }
    //不允许跳转
    decisionHandler(WKNavigationResponsePolicyCancel);
}


#pragma mark - WKUIDelegate
-(WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures{
    [_webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"https://www.baidu.com"]]];
    return _webView;
}

加载顺序如下:
iOS-WebKit之WKWebView(一个高性能的WebView)_第2张图片

你可能感兴趣的:(ios,webkit,webView)