WKWebView加载本地Web项目文件(WKWebView离线

2020-07-17  本文已影响0人  JoeyCen

随着苹果爸爸强制推动WKWebView替代UIWebView,各旧项目的替换工作随之而来,据说在2020年12月31日前未将UIWebView替换成WKWebView的项目将会被下架,而新项目在初次上线审核就会被卡。


首先我们先将Web项目打包成文件夹准备好

文件目录 拉进Web项目注意点 拉进Web项目后目录结构
 // 方法1

//获取html所在绝对路径        
NSString *htmlPath = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html" inDirectory:@"wk_test_project"];

 //生成url 此时并未拼接参数
 NSURL *fileUrl = [NSURL fileURLWithPath:htmlPath isDirectory:false];//isDirectory的意思是加载的路径是否是一个目录,传true时url最后会拼接上“ / ”,表示多一层目录结构。

//创建Components
 NSURLComponents *urlComponents = [NSURLComponents componentsWithURL:fileUrl resolvingAgainstBaseURL:NO];

 //创建参数数组
 NSArray *itemsArr = [NSArray arrayWithObjects:[NSURLQueryItem queryItemWithName:@"userID" value:@"1010"], [NSURLQueryItem queryItemWithName:@"baseUrl" value:@"https://molecular.com"],  nil];

 //设置参数
 [urlComponents setQueryItems:itemsArr];

 // 加载 本地路径加载必须用loadFileURL方法
 [_webView loadFileURL:urlComponents.URL allowingReadAccessToURL:urlComponents.URL];

 // 方法2

//获取html所在绝对路径
 NSString *htmlPath = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html" inDirectory:@"wk_test_project"];

//fileUrl拼接参数
 NSString* path  = [NSString stringWithFormat:@"file://%@?userID=1010&baseUrl=https://molecular.com",htmlPath];//转成file路径,并且拼上参数

// 加载 本地路径加载必须用loadFileURL方法
 [_webView loadFileURL:[NSURL URLWithString:path] allowingReadAccessToURL:[NSURL URLWithString:path]];
  1. 加载本地路径必须使用loadFileURL方法,如果用loadRequest的话在模拟器上会加载失败,在真机上加载速度缓慢,并会有“闪屏特效”!

  2. 切勿直接将路径用fileURLWithPath转为URL!此时获得的URL中的"?"被转码成"%3F"

NSString *filePath = [htmlPath stringByAppendingPathComponent:@"?userID=1010&baseUrl=https://molecular.com"];

NSURL *fileUrl = [NSURL fileURLWithPath: filePath];
//打印结果 “?”已被转码为“%3F”
loadUrl === " file:///var/containers/Bundle/Application/D066E775-9903-4945-8E74-AFA8055B8096/WKWebViewTestProject.app/wk_test_project/index.html%3FuserID=1010&baseUrl=https://molecular.com "
上一篇 下一篇

猜你喜欢

热点阅读