iOS_WKWebView加载工程内Bundle里面的文件,文件路径包含"#"

WKWebView加载本地文件,可以参考博文iOS_WKWebView加载本地网页

1、将HTML文件添加至工程内,本人是创建了一个LoactionHtml.Bundle用于存放html资源文件,获取工程文件内index.html的方式如下<每个人的工程文件目录不同,具体按照自己的来>

NSString *path = [[[NSBundle mainBundle] pathForResource:@"LoactionHtml" ofType:@"bundle"] stringByAppendingPathComponent:@"index.html"];

2、现在需要读取本地Bundle内带有"#“的路径,如下/index.html#/pages/activity/create/index
如果按照常用的写法,我们会发现加载失败,通过打印我们会发现路径内的”#"被编译成“%23”,这样WKWebView无法成功加载对应的路径。

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、如何避免路径内的"#“被编译成“%23”?
3.1、将获取NSURL的方式由fileURLWithPath:改为URLWithString:
3.2、在路径Path前拼接字符串"file://”
通过打印我们可以发现fileUrl内的"#"未被编译成“%23”,这样就可以成功加载。

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]];

两次fileUrl打印如下:

// 拼接file://
file:///Users/xxxxxxxxx/index.html#/pages/activity/create/index
// 未拼接file://
file:///Users/xxxxxxxxx/index.html%23/pages/activity/create/index

猜你喜欢

转载自blog.csdn.net/FlyingKuiKui/article/details/100053530