xcode loadHTMLString baseURL:nil 在 iOS5 中不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7981083/
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-09-14 22:18:46  来源:igfitidea点击:

loadHTMLString baseURL:nil not working in iOS5

xcodeuiwebviewios5

提问by moon

I got a problem with UIWebView. I want to render my own html code in UIWebView.

我遇到了 UIWebView 的问题。我想在 UIWebView 中呈现我自己的 html 代码。

if I use the below code, it's working fine.

如果我使用下面的代码,它工作正常。

    NSBundle *thisBundle = [NSBundle mainBundle];
    NSString *path = [thisBundle pathForResource:@"foo" ofType:@"html"];
    NSURL *baseURL = [NSURL fileURLWithPath:path];
    [self.webView loadHTMLString:@"foo.html" baseURL:baseURL];

I want to render the html with below code. But it's not working. foo.html contains exactly the same content with the NSString* one. Any hints? Thanks in advance. =)

我想用下面的代码呈现 html。但它不起作用。foo.html 包含与 NSString* 完全相同的内容。任何提示?提前致谢。=)

    NSString* one = @"<html><head><title></title></head><body><img src=\"image.jpg\"/></body></html>";
    [self.webView loadHTMLString:one baseURL:nil] ;

回答by Oliver

I use this code that works perfectly :

我使用这个完美的代码:

NSString* htmlContent = @"<html><head><title></title></head><body><img src='image.jpg' /></body></html>";
[self.webView loadHTMLString:htmlContent baseURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]]];

Bu sure that image.jpg is included into your project.

请确保 image.jpg 包含在您的项目中。

回答by Yuyutsu

create JS file demo.jsand add code

创建 JS 文件demo.js并添加代码

var hello = function(str){ ???? ?return str; };

var hello = function(str){ ???? ?return str; };

add UIWebView => To embed JavaScript in a dummy html file and load that into the UIWebView

添加 UIWebView => 将 JavaScript 嵌入到一个虚拟的 html 文件中并将其加载到 UIWebView

[self.webView loadHTMLString:@"<script src=\"demo.js\"></script>" ??????????????baseURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] resourcePath]]];

[self.webView loadHTMLString:@"<script src=\"demo.js\"></script>" ??????????????baseURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] resourcePath]]];

Here is the code to make JS call

这是进行JS调用的代码

NString *str=@"hi JavaScript";
NSString *function = [[NSString alloc] initWithFormat: @"hello(%@)", str];
NSString *result = [webView stringByEvaluatingJavaScriptFromString:function];

Now, there is one important safety tip to make this actually work: The UIWebView must actually be loaded a view. It doesn't have to be visible, but in order for the WebKit engine to execute the JS, it must be on a view.

现在,有一个重要的安全提示可以使它真正起作用:UIWebView 必须实际加载一个视图。它不一定是可见的,但为了让 WebKit 引擎执行 JS,它必须在视图上。