ios 载入html 尺寸,iOS开发webView加载本地html文件时参数带#的问题

首先, 将本地文件添加到项目中,在项目上右击选择Add Files to “项目名称”...,然后选择要添加的文件。

注意: 添加文件时Added folders:要选择Create folder references,否则获取路径时可能会返回nil

15303b92ca5d

在这里插入图片描述

添加后是这样的

15303b92ca5d

在这里插入图片描述

然后, 使用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了,页面内容也没有正确显示。

15303b92ca5d

在这里插入图片描述

解决办法:

在获取到的路径前拼接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中可以发现#并没有被转码,可以成功加载页面内容

15303b92ca5d

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值