首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何将本地html文件加载到UIWebView中

如何将本地html文件加载到UIWebView中
EN

Stack Overflow用户
提问于 2011-08-15 17:08:06
回答 13查看 198.1K关注 0票数 168

我正在尝试将html文件加载到我的UIWebView中,但它不起作用。这里是阶段:我的项目中有一个名为html_files的文件夹。然后,我在接口构建器中创建了一个webView,并在viewController中为它分配了一个插座。这是我用来附加html文件的代码:

代码语言:javascript
复制
-(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为空。如果能帮上忙我会很感激。

EN

回答 13

Stack Overflow用户

发布于 2011-08-15 17:34:21

这样,您就可以将项目资产(包)中的html文件加载到webView。

代码语言:javascript
复制
 UIWebView *web = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, 460)];
    [web loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] 
                                pathForResource:@"test" ofType:@"html"]isDirectory:NO]]];

也许这对你有用。

票数 40
EN

Stack Overflow用户

发布于 2011-08-15 18:55:41

我猜你需要先allocate并初始化你的webview::

代码语言:javascript
复制
- (void)viewDidLoad
{
    NSString *htmlFile = [[NSBundle mainBundle] pathForResource:@"sample" ofType:@"html" inDirectory:@"html_files"];
    NSData *htmlData = [NSData dataWithContentsOfFile:htmlFile];
    webView = [[UIWebView alloc] init];
    [webView loadData:htmlData MIMEType:@"text/html" textEncodingName:@"UTF-8" baseURL:[NSURL URLWithString:@""]];

    [super viewDidLoad];
}
票数 9
EN

Stack Overflow用户

发布于 2016-11-29 02:08:20

对于Swift 3和Swift 4:

代码语言:javascript
复制
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)
票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7063276

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档