如何将本地 html 文件加载到 UIWebView
我正在尝试将 html 文件加载到我的 UIWebView 中,但它不起作用.这是阶段:我的项目中有一个名为 html_files 的文件夹.然后我在界面构建器中创建了一个 webView,并在 viewController 中为其分配了一个插座.这是我用来附加 html 文件的代码:
I'm trying to load a html file into my UIWebView but it won't work. Here's the stage: I have a folder called html_files in my project. Then I created a webView in interface builder and assigned an outlet to it in the viewController. This is the code I'm using to append the html file:
-(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 是空白的.我很感激一些帮助.
That won't work and the UIWebView is blank. I'd appreciate some help.
使用 NSString 加载 html 文档可能更好,如下所示:
probably it is better to use NSString and load html document as follows:
目标 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
调用找到了资源.
Also check that the resource was found by pathForResource:ofType:inDirectory
call.