如何将本地 html 文件加载到 UIWebView [英] How to load local html file into UIWebView

查看:27
本文介绍了如何将本地 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.

这篇关于如何将本地 html 文件加载到 UIWebView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆