首先, 将本地文件添加到项目中,在项目上右击选择Add Files to “项目名称”...,然后选择要添加的文件。
注意: 添加文件时Added folders:要选择Create folder references,否则获取路径时可能会返回nil
在这里插入图片描述
添加后是这样的
在这里插入图片描述
然后, 使用WKWebView加载本地html文件(注意: 使用WKWebView需要导入#import )
CGFloat width = [UIScreen mainScreen].bounds.size.width;
CGFloat height = [UIScreen mainScreen].bounds.size.height;
WKWebView *webView = [[WKWebView alloc] init];
webView.frame = CGRectMake(0, 0, width, height);
// 获取本地html文件的绝对路径
NSString *path = [[NSBundle mainBundle] pathForResource:@"source/index" ofType:@"html"];
// 拼接参数
path = [path stringByAppendingString:@"#/xxx/xxx/xxx"];
NSURL *url = [NSURL fileURLWithPath:path];
NSLog(@"path:%@, url:%@", path, url);
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[webView loadRequest:request];
[self.view addSubview:webView];
打印path和url会发现,路径中的#被自动转码为%23了,页面内容也没有正确显示。
在这里插入图片描述
解决办法:
在获取到的路径前拼接file://
修改url生成方式:[NSURL URLWithString:path]
CGFloat width = [UIScreen mainScreen].bounds.size.width;
CGFloat height = [UIScreen mainScreen].bounds.size.height;
WKWebView *webView = [[WKWebView alloc] init];
webView.frame = CGRectMake(0, 0, width, height);
// 获取本地html文件的绝对路径
NSString *path = [[NSBundle mainBundle] pathForResource:@"source/index" ofType:@"html"];
// 拼接参数
path = [path stringByAppendingString:@"#/xxx/xxx/xxx"];
path = [@"file://" stringByAppendingString:path];
// NSURL *url = [NSURL fileURLWithPath:path];
NSURL *url = [NSURL URLWithString:path];
NSLog(@"path:%@, url:%@", path, url);
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[webView loadRequest:request];
[self.view addSubview:webView];
在打印的path和url中可以发现#并没有被转码,可以成功加载页面内容
在这里插入图片描述