WKWebView載入本地資源loadData:MIMEType:characterEncodingName:baseURL:
#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]];
NSString *htmlPath = [[NSBundle mainBundle] pathForResource:@"aboard" ofType:@"html"];
NSData *htmlData = [[NSData alloc] initWithContentsOfFile:htmlPath];
[self.webView loadData:htmlData MIMEType:@"text/html" characterEncodingName:@"UTF-8" baseURL:url];
}
#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