【问题标题】:How do I pass data to javascript from Xcode in UIWebView?如何在 UIWebView 中将数据从 Xcode 传递给 javascript?
【发布时间】:2014-07-15 18:34:47
【问题描述】:

我有一个虚拟 HTML 文件,用于加载我的 javascript 文件,以便我可以使用其中的函数:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
   <head>
      <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>

      <script type="text/javascript"      src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>
      <script type="text/javascript" src="js/makeTable.js"></script>

    </head>
    <body>

    </body>
</html>

我想通过对 UIWebView 使用 stringByEvaluatingJavascriptFromString 函数,在我的 Xcode 代码中使用 makeTable.js 中的函数。我需要传递的所有参数都被正确传递,这是我在 Xcode 中使用调试器时知道的。我不知道为什么 javascript 没有加载,我尝试使用警报来查看它是否加载。

在 Xcode 中,当我尝试在 viewDidLoad 方法中加载我的 html 文件时,我的代码如下所示

- (void)viewDidLoad
{
    [super viewDidLoad];

    NSString *htmlPath = [[NSBundle mainBundle] pathForResource:@"loadingWeb"
                                                     ofType:@"html"
                                                inDirectory:@"/htdoc" ];

    NSString *html = [NSString stringWithContentsOfFile:htmlPath
                                           encoding:NSUTF8StringEncoding
                                              error:nil];

    [_webView loadHTMLString:html
                baseURL:[NSURL fileURLWithPath:
                         [NSString stringWithFormat:@"%@/htdoc/",
                          [[NSBundle mainBundle] bundlePath]]]];

    [_webView loadHTMLString:@"<script>alertMeWithMyCustomFunction('I am');</script>" baseURL:[NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/htdoc/",[[NSBundle mainBundle] bundlePath]]]];
}

在 UIWebView 中,什么都没有显示,只是一个空白屏幕。在 makeTable.js 文件中,alertMeWithMyCustomFunction 方法如下所示:

function alertMeWithMyCustomFunction(text) {
    alert(text+' -> in lib.js');
}        

基本上,我如何使用 javascript 函数并使用 stringByEvaluatingJavascriptFromString 方法从 Xcode 传递参数,因为最后我希望这行代码能够工作:

NSString* script = [NSString stringWithFormat:@"table = makeTable( %d, %@, %@, %@);", i, [albumObj.moments[i] latitude], [albumObj.moments[i] longitude], jpgPath];
[_webView stringByEvaluatingJavaScriptFromString:script];  

我想使用的所有 JS 函数都在 makeTable.js 文件中。我只需要能够在 UIWebView 中与这个文件进行交互,因为我所有的数据都在 Xcode 中,但我需要在 JS 中使用它

【问题讨论】:

    标签: javascript ios objective-c xcode uiwebview


    【解决方案1】:

    问题是loadHTMLString:baseURL: 在添加新的 HTML 之前删除了之前在 UIWebView 中的 HTML。因此,当您在viewDidLoad 中再次调用loadHTMLString:baseURL: 以注入脚本标记时,它会清除您刚刚从loadingWeb.html 添加的HTML。为什么不使用stringByEvaluatingJavaScriptFromString: 而不是注入脚本标签?

    另外,如果您不知道,您可以使用 Safari 中的网络检查器在您的 UIWebView 中检查和调试您的 HTML/CSS/JS。在使用 UIWebViews 时,这对我来说是救命稻草。 有关说明,请参阅this answer。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-08-30
      • 2011-10-16
      • 1970-01-01
      • 2016-07-15
      • 1970-01-01
      • 1970-01-01
      • 2016-04-12
      • 2016-01-01
      相关资源
      最近更新 更多