iOS 如何加载本地html文件

html-css012

iOS 如何加载本地html文件,第1张

很简单

如下图所示

其中

部分是你的html文件相对于整个工程的路径

例如下面这个工程构成图:

相关文件最好以文件方式导入而不是group

CSDN: iOS 如何加载本地html文件

1、将html文件夹拖入项目根目录下,选择引用(蓝色文件夹)

2、获取index.html所在的路径

3、webView调用loadFileURL:allowingReadAccessToURL:方法加载

如果需要拼接额外参数,需要手动拼接地址,直接用fileURLWithPath生成的链接,会进行编码

NSString *basePath = [NSString stringWithFormat: @"%@/%@", [[NSBundle mainBundle] bundlePath], @"index.html所在的文件夹"]

NSURL *baseUrl = [NSURL fileURLWithPath: basePath isDirectory: YES]

NSString *filePath = [NSString stringWithFormat: @"file://%@/index.html#/?xxx=%@&sss=%@", basePath, @"xxx", @"sss"]

NSURL *fileUrl = [NSURL URLWithString: filePath]

[_webView loadFileURL: fileUrl allowingReadAccessToURL: baseUrl]

将css,html,js 所在的文件夹拖入项目的时候会有两种情况

一个是 Create groups for any added folders (创建虚拟结构-包结构)

一个是 Create folder references for any added folders (创建实体结构)

第一种是绝对路径 文件夹拖入为黄色

NSURL*fileURL = [[NSBundle mainBundle] URLForResource:@"index.html"withExtension:nil]

本地html中加载图片,js,css资源也应该使用绝对路径就行了

如 <script type="text/javascript" src="index.js"></script>

第二种是相对路径 文件夹拖入为蓝色

NSURL*fileURL = [[NSBundle mainBundle] URLForResource:@"file/index.html"withExtension:nil]

file为本地html所在文件夹

本地html中加载图片,js,css资源也应该使用相对路径

如 <script type="text/javascript" src="js/index.js"></script>