iOS中wkwebview加载本地html的要点

时间:2023-03-08 18:38:02
项目中有些页面,我采用了html页面开发,然后用wkwebview加载的设计。在加载过程中遇见了一些问题,在这里进行一些记载和讨论。如有不同意见欢迎进行评论沟通。
问题时候这样的:
在webview的loadrequest中不能加载出来
webview.m中的代码:
//self.PageUrlString:加载的链接地址 if (self.PageUrlString) {
[self.wekView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.PageUrlString]]];
}
获取html的代码:
  1. pathForResource
webVC.PageUrlString = [[NSBundle mainBundle] pathForResource:@"connectUs" ofType:@"html"]
结果:并不能正常加载,如下图

iOS中wkwebview加载本地html的要点

经过研究,换用了获取文件路径的方法,就可以正常加载了

2.URLForResource

 webVC.fileUrl = [[NSBundle mainBundle] URLForResource:@"connectUs.html" withExtension:nil];

讨论

1.pathForResource 和 2.URLForResource 获取结果的区别

打印结果

iOS中wkwebview加载本地html的要点

结果中可以看出来,

1.pathForResource 出来的结果是纯路径

2.URLForResource 出来的加file协议的路径

结论:

wkwebview 中loadrequest加载的url应该是是设置协议的路径

调整:

  webVC.PageUrlString = [NSString stringWithFormat:@"file://%@",[[NSBundle mainBundle] pathForResource:@"connectUs" ofType:@"html"]];

  webVC.fileUrl = [[NSBundle mainBundle] URLForResource:@"connectUs.html" withExtension:nil];