如何將本地html文件加載到UIWebView中我正在嘗試將html文件加載到我的UIWebView中,但它不起作用。這是舞臺(tái):我的項(xiàng)目中有一個(gè)名為html_files的文件夾。然后我在界面構(gòu)建器中創(chuàng)建了一個(gè)webView,并在viewController中為它分配了一個(gè)插座。這是我用來(lái)附加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貢獻(xiàn)2041條經(jīng)驗(yàn) 獲得超4個(gè)贊
可能最好使用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幾乎沒(méi)有變化:
let htmlFile = Bundle.main.path(forResource: "intro", ofType: "html")let html = try? String(contentsOfFile: htmlFile!, encoding: String.Encoding.utf8)webView.loadHTMLString(html!, baseURL: nil)
你試過(guò)了嗎?
還要檢查是否通過(guò)pathForResource:ofType:inDirectory
調(diào)用找到了資源。

素胚勾勒不出你
TA貢獻(xiàn)1827條經(jīng)驗(yàn) 獲得超9個(gè)贊
對(duì)于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 關(guān)注
- 657 瀏覽
添加回答
舉報(bào)
0/150
提交
取消