"进样" Objective-C数据加载到一个加载本地HTML文件的UIWebView?

时间:2011-12-10 14:55:03

标签: iphone objective-c uiwebview

我正在尝试加载一个带有本地HTML / CSS的UIWebView,它看起来像一个营养标签。问题是,食物的数据位于我的iPhone应用程序内。我是否必须将所有HTML放入一个巨大的NSString对象并将我的数据连接到其中,或者是否有办法从本地.html文件加载HTML,但不知何故“注入”存储在Objective-中的数据C进去了吗?

4 个答案:

答案 0 :(得分:2)

如果要注入的数据是“安全的”,您可以将“巨大的NSString对象”构造为格式字符串,并添加%@标记,并使用stringWithFormat:执行注入单动。这就是我在TidBITS新闻应用程序中构建页面的方式,使用的所有内容都来自RSS。这真的很无痛。

答案 1 :(得分:1)

您可以使用NSData的方法dataWithContentsOfFile加载基本的html,然后使用javascript以您需要的方式修改html。

代码看起来像这样(使用此example):

NSString *path = [[NSBundle mainBundle] pathForResource:@"food" ofType:@"html"]; 
NSData *data = [NSData dataWithContentsOfFile:path];
if (data) {  
    [webView loadData:data MIMEType:@"text/html" textEncodingName:@"UTF-8"];  
}
[webView stringByEvaluatingJavaScriptFromString:@"var script = document.createElement('script');"
                     "script.type = 'text/javascript';"
                     "script.text = \"function myFunction() { "
                        "var field = document.getElementById('field_3');"
                        "field.value='Calling function - OK';"
                     "}\";"
                     "document.getElementsByTagName('head')[0].appendChild(script);"];

[webView stringByEvaluatingJavaScriptFromString:@"myFunction();"];

答案 2 :(得分:0)

我会混合两者 - 在您加载的应用程序中有一个HTML文件,然后在将其提供给UIWebView之前替换其中的某些字符串。例如,您可以拥有这样的文件

<html>
<head>
<title><!--foodName--></title>
</head>
<body>
<h1><!--foodName--></h1>
<p>Calories / 100g: <!--foodCalories--></p>
</body>
</html>

您将其加载到Cocoa中,然后用您想要的实际值替换您的特殊占位符注释。

NSDictionary *substitutions = [NSDictionary dictionaryWithObjectsAndKeys: 
                               @"Carrots", @"foodName",
                               [NSNumber numberWithInt:20], @"foodCalories",
                               // add more as needed
                               nil];

NSMutableString *html = [NSMutableString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"foodCard" ofType:@"html"] 
                                                         encoding:NSUTF8StringEncoding
                                                            error:nil];

for(NSString *substitutionKey in substitutions)
{
    NSString *substitution = [[substitution objectForKey:substitutionKey] description];
    NSString *searchTerm = [NSString stringWithFormat:@"<!--%@-->", substitutionKey];

    [html replaceOccurrencesOfString:searchTerm withString:substitution options:0 range:NSMakeRange(0, [html length])];
}

[webView loadHTMLString:html baseURL:[[NSBundle mainBundle] resourceURL]];

答案 3 :(得分:0)

从iOS 2开始,您可以在UIWebView子类中使用- (NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)script来在Webview中执行JS脚本。这是从应用程序的“Objective-C部分”注入数据的最佳方式。

Cf:https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIWebView_Class/#//apple_ref/occ/instm/UIWebView/stringByEvaluatingJavaScriptFromString