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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7063276/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 21:06:10  来源:igfitidea点击:

How to load local html file into UIWebView

iosobjective-ciphonecocoa-touchuiwebview

提问by madcoderz

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:

我正在尝试将 html 文件加载到我的 UIWebView 中,但它不起作用。这是阶段:我的项目中有一个名为 html_files 的文件夹。然后我在界面构建器中创建了一个 webView,并在 viewController 中为其分配了一个插座。这是我用来附加 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];
}

That won't work and the UIWebView is blank. I'd appreciate some help.

那行不通, UIWebView 是空白的。我很感激一些帮助。

回答by user478681

probably it is better to use NSString and load html document as follows:

可能最好使用 NSString 并按如下方式加载 html 文档:

Objective-C

目标-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) 

Swift 3 has few changes:

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)

Did you try?

你试过了吗?

Also check that the resource was found by pathForResource:ofType:inDirectorycall.

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

回答by Neal Ehardt

EDIT 2016-05-27- loadRequestexposes "a universal Cross-Site Scripting vulnerability."Make sure you own every single asset that you load. If you load a bad script, it can load anything it wants.

编辑 2016-05-27-loadRequest暴露了“一个通用的跨站脚本漏洞”。确保您拥有加载的每一项资产。如果你加载了一个糟糕的脚本,它可以加载它想要的任何东西。

If you need relative links to work locally, use this:

如果您需要相关链接在本地工作,请使用以下命令:

NSURL *url = [[NSBundle mainBundle] URLForResource:@"my" withExtension:@"html"];
[webView loadRequest:[NSURLRequest requestWithURL:url]];

The bundle will search all subdirectories of the project to find my.html. (the directory structure gets flattened at build time)

该包将搜索项目的所有子目录以找到my.html. (目录结构在构建时变平)

If my.htmlhas the tag <img src="some.png">, the webView will load some.pngfrom your project.

如果my.html有标签<img src="some.png">,则 webViewsome.png将从您的项目中加载。

回答by AJPatel

by this you can load html file which is in your project Assets(bundle) to webView.

通过这种方式,您可以将项目 Assets(bundle) 中的 html 文件加载到 webView。

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

may be this is useful to you.

可能这对你有用。

回答by Saran

I guess you need to allocateand init your webviewfirst::

我想你需要allocate初始化你的webview第一个::

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

回答by Durai Amuthan.H

A Simple Copy-Paste code snippet:

一个简单的复制粘贴代码片段:

-(void)LoadLocalHtmlFile:(NSString *)fileName onWebVu:(UIWebView*)webVu
{
    [webVu loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle]pathForResource:fileName ofType:@"html"]isDirectory:NO]]];
}

Note:

笔记:

Make sure the html file's Target membershipis checked otherwise following exception will get thrown :-

确保检查 html 文件的目标成员资格,否则将引发以下异常:-

enter image description here

在此处输入图片说明

Terminating app due to uncaught exception

由于未捕获的异常而终止应用程序

'NSInvalidArgumentException', reason: '*** -[NSURL initFileURLWithPath:isDirectory:]: nil string parameter'

'NSInvalidArgumentException', reason: '*** -[NSURL initFileURLWithPath:isDirectory:]: nil string parameter'

回答by pableiros

For Swift 3 and Swift 4:

对于 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)

回答by Raees Valapuram Madathil

UIWebView *web=[[UIWebView alloc]initWithFrame:self.view.frame];
    //[self.view addSubview:web];
    NSString *filePath=[[NSBundle mainBundle]pathForResource:@"browser_demo" ofType:@"html" inDirectory:nil];
    [web loadRequest:[NSURLRequest requestWhttp://stackoverflow.com/review/first-postsithURL:[NSURL fileURLWithPath:filePath]]];

回答by user1173142

May be your HTML file doesn't support UTF-8 encoding, because the same code is working for me.

可能是您的 HTML 文件不支持 UTF-8 编码,因为相同的代码对我有用。

Or u can also these line of code:

或者你也可以使用这些代码行:

NSString *htmlFile = [[NSBundle mainBundle] pathForResource:@"Notes For Apple" ofType:@"htm" inDirectory:nil];
NSString* htmlString = [NSString stringWithContentsOfFile:htmlFile encoding:NSUTF8StringEncoding error:nil];
[WebView loadHTMLString:htmlString baseURL:nil];

回答by Abhilash Reddy kallepu

Here the way the working of HTML file with Jquery.

这是使用 Jquery 处理 HTML 文件的方式。

 _webview=[[UIWebView alloc]initWithFrame:CGRectMake(0, 0, 320, 568)];
    [self.view addSubview:_webview];

    NSString *filePath=[[NSBundle mainBundle]pathForResource:@"jquery" ofType:@"html" inDirectory:nil];

    NSLog(@"%@",filePath);
    NSString *htmlstring=[NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];

    [_webview loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:filePath]]];
                         or
    [_webview loadHTMLString:htmlstring baseURL:nil];

You can use either the requests to call the HTML file in your UIWebview

您可以使用请求来调用 UIWebview 中的 HTML 文件

回答by ppalancica

Make sure "html_files" is a directory in your app's main bundle, and not just a group in Xcode.

确保“html_files”是应用程序主包中的一个目录,而不仅仅是 Xcode 中的一个组。