程序员iOS开发进阶

WKWebView 简单实现

2017-11-02  本文已影响0人  晴朗Nic

随着需求的功能不断提高,原来的UIWebView的是不能满足实现更加强大的加载功能,WKWebView将会代替UIWebView成为加载HTML页面的时代宠儿,下面就是简单实现WKWebView,WKWebView非常强大,以后慢慢给大家讲。

//一、在头部倒入 #import <WebKit/WebKit.h>
#import <WebKit/WebKit.h>

#define RequestUrl @"http://www.jianshu.com"

//二、遵循代理 WKUIDelegate,WKNavigationDelegate
@interface ViewController ()<WKUIDelegate,WKNavigationDelegate>

@property (nonatomic, weak) WKWebView *gobalWebView;
@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
//三、实例化WKWebView
    WKWebView *webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
    [webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:RequestUrl]]];
    webView.UIDelegate = self;
    webView.navigationDelegate = self;
    [self.view addSubview:webView];
    self.gobalWebView = webView;
}

//遵循代理
#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 didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error
{
    NSLog(@"页面加载失败.......");
}

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

//要住这个代理一定要回调回去不然会奔溃,回调WKNavigationResponsePolicyAllow表示可以跳转,回调WKNavigationResponsePolicyCancel表示不可以跳转.
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(nonnull WKNavigationResponse *)navigationResponse decisionHandler:(nonnull void (^)(WKNavigationResponsePolicy))decisionHandler
{
    NSLog(@"在收到响应后,决定是否跳转");
    decisionHandler(WKNavigationResponsePolicyAllow);
    return;
    /*//利用这个提取的URL来决应不应该跳转例如:我这里根据url来判断
    if ([navigationResponse.response.URL.absoluteString isEqualToString:RequestUrl])
    {
        //回调回去可以跳转
        decisionHandler(WKNavigationResponsePolicyAllow);
        return;
    }
    //回调回去不可以跳转
    decisionHandler(WKNavigationResponsePolicyCancel);*/
}

//要住这个代理一定要回调回去不然会奔溃,回调WKNavigationResponsePolicyAllow表示可以跳转,回调WKNavigationResponsePolicyCancel表示不可以跳转.
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
{
    NSLog(@"在发送请求之前,决定是否跳转");
    decisionHandler(WKNavigationActionPolicyAllow);
    return;
    /*//利用这个提取的URL来决应不应该跳转例如:我这里根据url来判断
    if ([navigationAction.request.URL.absoluteString isEqualToString:RequestUrl])
    {
        decisionHandler(WKNavigationActionPolicyAllow);
        return;
    }
    //回调回去不可以跳转
    decisionHandler(WKNavigationActionPolicyCancel);*/
}

上一篇 下一篇

猜你喜欢

热点阅读