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中可以发现#并没有被转码,可以成功加载页面内容

在这里插入图片描述
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Swift1> Swift和OC的区别1.1> Swift没有地址/指针的概念1.2> 泛型1.3> 类型严谨 对...
    cosWriter阅读 11,144评论 1 32
  • ¥开启¥ 【iAPP实现进入界面执行逐一显】 〖2017-08-25 15:22:14〗 《//首先开一个线程,因...
    小菜c阅读 6,537评论 0 17
  • 此刻我脑子中有好几条丝线,相互交叉,纷乱,面前的书籍从眼睛里看进去好像能从脑子后头飘出去,没有一丝留下的迹象。...
    八十多个钢镚儿阅读 178评论 1 1
  • 当夜幕降临,你是否还在挑灯加班,或者是回家的地铁上,还是在自己的小窝里思绪万千。 工作繁忙呢就做好计划和清单一件件...
    南方有自渡阅读 268评论 0 0
  • 原创:小天沐森读书前天 以梦为马,诗酒趁年华;韶华易逝,追梦不负初心。 01 “拼高三一年,赢无悔人生!” “今朝...
    沐森读书阅读 246评论 0 0