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

查看:121
本文介绍了如何加载本地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:

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]];

Swift

let htmlFile = NSBundle.mainBundle().pathForResource("fileName", ofType: "html")
let html = try? String(contentsOfFile: htmlFile!, encoding: NSUTF8StringEncoding)
webView.loadHTMLString(html!, baseURL: nil) 

还要检查是否找到资源pathForResource:ofType:inDirectory 调用。

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

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