任何想法如何从OBJ-C调用和发送参数到JS函数
让我们在我的HTML中说我有JS
function showPieChart(parameter1,parameter2){...}
从viewDidLoad中我的obj c类我想调用这个函数。有什么想法或例子吗?提前谢谢......
答案 0 :(得分:3)
在UIWebViewDelegate的webViewDidFinishLoad:中添加:
NSString *functionCall = [NSString stringWithFormat:@"showPieChart(%@,%@)", param1, param2];
NSString *result = [webView stringByEvaluatingJavaScriptFromString:functionCall];
要将视图控制器设置为UIWebView的委托,您必须将<UIWebViewDelegate>
协议添加到@interface
标头,并将UIWebView的委托字段链接到视图控制器。
如果您的参数位于数组中,则可以使用[array objectForIndex:i]
(i是每个参数的索引)逐个提取它们,或者使用componentsJoinedByString:
NSArray *params = [NSArray arrayWithObjects:@"a",@"b",nil];
NSString *functionCall = [NSString stringWithFormat:@"showPieChart(%@)", [params componentsJoinedByString:@","]];
答案 1 :(得分:1)
1)实现UIWebViewDelegate
2)覆盖
- (BOOL)webView:(UIWebView *)aWebView shouldStartLoadWithRequest:(NSURLRequest *)请求navigationType:(UIWebViewNavigationType)navigationType方法..
3)在此方法中,您将请求与定义的protocole进行比较。
示例:
NSString * requestString = [[request URL] absoluteString]; NSArray * components = [requestString componentsSeparatedByString:@“:”];
if ([components count] > 1 &&
[(NSString *)[components objectAtIndex:0] isEqualToString:@"myapp"]) {
if([(NSString *)[components objectAtIndex:1] isEqualToString:@"myfunction"])
{
NSLog([components objectAtIndex:2]); // param1
NSLog([components objectAtIndex:3]); // param2
// Call your method in Objective-C method using the above...
}
return NO;
}
4)修改你的javascript文件以创建protocole:
function showPieChart(parameter1,parameter2) { window.location =“myapp:”+“myfunction:”+ param1 +“:”+ param2;
}
资源:http://www.codingventures.com/2008/12/using-uiwebview-to-render-svg-files/
答案 2 :(得分:0)
我猜你有一个加载了网页的UIWebView。要执行JavaScript,请执行以下操作:
NSString *result = [_webView stringByEvaluatingJavaScriptFromString:@"showPieChart()"];