iOS开发webView加载本地html文件时参数带#的问题

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

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

在这里插入图片描述

添加后是这样的

在这里插入图片描述

然后, 使用WKWebView加载本地html文件(注意: 使用WKWebView需要导入#import <WebKit/WebKit.h>

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

在这里插入图片描述

解决办法:

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

在这里插入图片描述

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

jinrui_w

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值