隨著蘋果爸爸強制推動WKWebView替代UIWebView,各舊項目的替換工作隨之而來,據說在2020年12月31日前未將UIWebView替換成WKWebView的項目將會被下架,而新項目在初次上線審核就會被卡。
- 本文主要介紹一下如何在WKWebView加載本地Web項目,包括項目中的js以及css文件。
首先我們先將Web項目打包成文件夾準備好
文件目錄
- 將項目拖進Xcode,并選擇"create folder references" ,由于前端代碼引用文件,圖標什么的都是使用的路徑。所以用第一種方式就會發現用webview加載前端頁面時,頁面是亂的,因為加載不到指定路徑的js和css文件。
拉進Web項目注意點
拉進Web項目后目錄結構
-
本地html帶參數加載方法1(NSURLComponents插入參數)
// 方法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];
-
本地html帶參數加載方法2(stringWithFormat拼接絕對路徑和參數)
// 方法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]];
-
要點
加載本地路徑必須使用loadFileURL方法,如果用loadRequest的話在模擬器上會加載失敗,在真機上加載速度緩慢,并會有“閃屏特效”!
切勿直接將路徑用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 "