WKWebView loads local files, you can refer to the blog post iOS_WKWebView to load local web pages
1. Add the HTML file to the project. I created a LoactionHtml.Bundle
file to store the html resource file. index.html
The way to get the project file is as follows. <Each person’s project file directory is different, according to your own>
NSString *path = [[[NSBundle mainBundle] pathForResource:@"LoactionHtml" ofType:@"bundle"] stringByAppendingPathComponent:@"index.html"];
2. Now we need to read the path with "#" in the local Bundle, as follows /index.html#/pages/activity/create/index
,
if we follow the common writing method, we will find that the loading fails, and by printing we will find that the "#" in the path is compiled into "%23", In this way, WKWebView cannot successfully load the corresponding path.
NSString *path = [[[NSBundle mainBundle] pathForResource:@"LoactionHtml" ofType:@"bundle"] stringByAppendingPathComponent:@"index.html#pages/activity/create/index"];
NSURL *fileUrl = [NSURL fileURLWithPath:path];
// WKWebView加载fileUrl
[self.webView loadRequest:[NSURLRequest requestWithURL:fileUrl]];
3. How to avoid "#" in the path from being compiled into "%23"?
3.1. Change the way fileURLWithPath:
to get NSURL URLWithString:
;
3.2. Path
Splice the string "file://" before the path .
By printing, we can find that the "#" in fileUrl has not been compiled into "%23", so that it can be successfully loaded .
NSString *path = [[[NSBundle mainBundle] pathForResource:@"LoactionHtml" ofType:@"bundle"] stringByAppendingPathComponent:@"index.html#pages/activity/create/index"];
// 在path前拼接字符串"file://"
NSURL *fileUrl = [NSURL URLWithString:[@"file://" stringByAppendingString:path]];
// WKWebView加载fileUrl
[self.webView loadRequest:[NSURLRequest requestWithURL:fileUrl]];
The fileUrl prints twice as follows:
// 拼接file://
file:///Users/xxxxxxxxx/index.html#/pages/activity/create/index
// 未拼接file://
file:///Users/xxxxxxxxx/index.html%23/pages/activity/create/index