WKWebView加载网络资源

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sndongcheng/article/details/82747776

#import "ViewController.h"

#import <WebKit/WebKit.h>

@interface ViewController ()<WKNavigationDelegate>

@property(nonatomic,strong) WKWebView* webView;

@end

@implementation ViewController

- (void)viewDidLoad {

    [super viewDidLoad];

    //sreen是主屏幕的范围

    CGRect screen = [[UIScreen mainScreen] bounds];

    

    //按钮栏

    CGFloat buttonBarWidth = 300;

    UIView* buttonBar = [[UIView alloc]initWithFrame:CGRectMake((screen.size.width - buttonBarWidth)/2,50, buttonBarWidth, 30)];

    buttonBar.backgroundColor = [UIColor grayColor];

    [self.view addSubview:buttonBar];

    

    //按钮栏按钮

    UIButton* buttonLoadRequest = [UIButton buttonWithType:UIButtonTypeSystem];

    [buttonLoadRequest setTitle:@"wedding" forState:UIControlStateNormal];

    buttonLoadRequest.frame = CGRectMake((buttonBarWidth-80)/2, 0, 80, 30);

    [buttonLoadRequest addTarget:self action:@selector(testLoadRequest:) forControlEvents:UIControlEventTouchUpInside];

    [buttonBar addSubview:buttonLoadRequest];

    

    //添加WKWebView到视图中

    self.webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 95, screen.size.width, screen.size.height-80)];

    [self.view addSubview:self.webView];

    

}

//实现按钮点击事件方法,实现网络资源加载,一共分为四步

-(void)testLoadRequest:(id)sender{

    NSURL * url = [NSURL URLWithString:@"http://www.studynumber.com"];

    NSURLRequest * request = [NSURLRequest requestWithURL:url];

    [self.webView loadRequest:request];

    self.webView.navigationDelegate = self;

}

//下面的委托协议是固定不变的

#pragma mark -- 实现WKNavigationDelegate委托协议

//开始加载时调用

-(void)webView:(WKWebView *)webView didStartProvisionalNavigation:(null_unspecified WKNavigation *)navigation{

    NSLog(@"开始加载");

}

//当内容开始返回时调用

-(void)webView:(WKWebView *)webView didCommitNavigation:(null_unspecified WKNavigation *)navigation{

    NSLog(@"内容开始返回");

}

//加载完成之后调用

-(void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation{

    NSLog(@"加载完成");

}

//加载失败时调用

-(void)webView:(WKWebView *)webView didFailLoadWithError:(nonnull NSError *)error{

    NSLog(@"加载失败 error : %@",error.description);

}

- (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

@end

猜你喜欢

转载自blog.csdn.net/sndongcheng/article/details/82747776