如何將本地html文件加載到UIWebView中我正在嘗試將html文件加載到我的UIWebView中,但它不起作用。這是舞臺:我的項目中有一個名為html_files的文件夾。然后我在界面構建器中創建了一個webView,并在viewController中為它分配了一個插座。這是我用來附加html文件的代碼:-(void)viewDidLoad{
NSString *htmlFile = [[NSBundle mainBundle] pathForResource:@"sample" ofType:@"html" inDirectory:@"html_files"];
NSData *htmlData = [NSData dataWithContentsOfFile:htmlFile];
[webView loadData:htmlData MIMEType:@"text/html" textEncodingName:@"UTF-8" baseURL:[NSURL URLWithString:@""]];
[super viewDidLoad];}這不起作用,UIWebView是空白的。我很感激一些幫助。
3 回答

縹緲止盈
TA貢獻2041條經驗 獲得超4個贊
可能最好使用NSString并加載html文件,如下所示:
Objective-C的
NSString *htmlFile = [[NSBundle mainBundle] pathForResource:@"sample" ofType:@"html"];NSString* htmlString = [NSString stringWithContentsOfFile:htmlFile encoding:NSUTF8StringEncoding error:nil];[webView loadHTMLString:htmlString baseURL: [[NSBundle mainBundle] bundleURL]];
迅速
let htmlFile = NSBundle.mainBundle().pathForResource("fileName", ofType: "html")let html = try? String(contentsOfFile: htmlFile!, encoding: NSUTF8StringEncoding)webView.loadHTMLString(html!, baseURL: nil)
Swift 3幾乎沒有變化:
let htmlFile = Bundle.main.path(forResource: "intro", ofType: "html")let html = try? String(contentsOfFile: htmlFile!, encoding: String.Encoding.utf8)webView.loadHTMLString(html!, baseURL: nil)
你試過了嗎?
還要檢查是否通過pathForResource:ofType:inDirectory
調用找到了資源。

素胚勾勒不出你
TA貢獻1827條經驗 獲得超9個贊
對于Swift 3和Swift 4:
let htmlFile = Bundle.main.path(forResource: "name_resource", ofType: "html")let html = try! String(contentsOfFile: htmlFile!, encoding: String.Encoding.utf8)self.webView.loadHTMLString(html, baseURL: nil)
- 3 回答
- 0 關注
- 658 瀏覽
添加回答
舉報
0/150
提交
取消