WKWebView加载本地资源loadHTMLString:baseURL:

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

#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{

    //url是固定不变的

    NSURL * url = [NSURL fileURLWithPath:[[NSBundle mainBundle]bundlePath]];

    //htmlPath和error才能得到html   步骤一步骤二步骤三(第三步要注意网页编码不要错)

    NSString *htmlPath = [[NSBundle mainBundle] pathForResource:@"aboard" ofType:@"html"];

    NSError *error = nil;

    NSString *html = [[NSString alloc] initWithContentsOfFile:htmlPath encoding:NSUTF8StringEncoding error:&error];

    if (error == nil) {

        [self.webView loadHTMLString:html baseURL:url];

    }

    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/82749389