1. 程式人生 > >ios UIWebView 載入本地html,js,css檔案的問題

ios UIWebView 載入本地html,js,css檔案的問題

iOS 開發有時候我們會用UIWebView載入本地html,js,css 檔案,載入的方法:

 NSString *filePath = [[NSBundle mainBundle]pathForResource:@"index" ofType:@"html"];
    NSString *htmlString = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
    [webView loadHTMLString:htmlString baseURL:[NSURL URLWithString:filePath]]
;

執行後發現只加載了html檔案,而cssjs檔案沒有載入,
工程中html,js,css 路徑如下:
這裡寫圖片描述

html檔案在www檔案下,然後列印html檔案的完整路徑:
/private/var/mobile/Containers/Bundle/Application/043B3B79-E397-4913-9B44-CBBC12A00FA5/OcSwift.app/index.html
index.html這個檔案前面沒有www檔案路徑,這是因為編譯器打包時去掉了這些資料夾,所以js的路徑變成了
/private/var/mobile/Containers/Bundle/Application/043B3B79-E397-4913-9B44-CBBC12A00FA5/OcSwift.app/index.js
引用js檔案時,使用<script type="text/javascript" src="js/index.js"></script>

就會找不到index.js檔案。
要改為<script type="text/javascript" src="index.js"></script> 就可以了。
但是如果這樣在web端開發的時候就會載入不到js和css檔案,一種解決方法是,新增資料夾的時候,選擇Create folder references,如下圖:
這裡寫圖片描述
新增後:
這裡寫圖片描述

資料夾是藍色的,而不是黃色,這種情況下index.html的路徑不能通過[[NSBundle mainBundle]pathForResource:@"index" ofType:@"html"]; 獲取到,需要手動拼接路徑,如下:

/private/var/mobile/Containers/Bundle/Application/871B4041-5CCE-4C94-935C-16C6C31D62B9/OcSwift.app/www/index.html

另一種解決方法是把整個www的資料夾copy到Document檔案下面,這樣就不會有這種問題,