WKWebView加载本地资源loadData:MIMEType:characterEncodingName:baseURL:

本文档展示了如何在iOS应用中使用WKWebView组件加载本地HTML文件。通过创建WKWebView实例,设置MIMEType和字符编码,然后调用`loadData: MIMEType: characterEncodingName: baseURL:`方法来加载本地HTML资源。同时,还实现了WKNavigationDelegate协议以监听加载过程中的各种状态,包括开始加载、内容返回、加载完成和加载失败的情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

 

#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

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值