开发者

iPhone: call and send parameters to JS function from OBJ-C

Any idea how to call and send parameters to JS function from OBJ-C ??

Lets say in my html I have JS

function showPieChart (param开发者_运维百科eter1, parameter2) { ... }

and from my obj c class in viewDidLoad I want to call this function. Any idea or examples ? Thanks in advance...


Add this in the webViewDidFinishLoad: of the UIWebViewDelegate:

NSString *functionCall = [NSString stringWithFormat:@"showPieChart(%@,%@)", param1, param2];
NSString *result = [webView stringByEvaluatingJavaScriptFromString:functionCall];

To set a view controller as delegate of a UIWebView, you have to add the <UIWebViewDelegate> protocol to the @interface header and link the delegate field of the UIWebView to the view controller.

If your parameters are inside an array, you can extract them one by one with [array objectForIndex:i] (i being the index for each parameter) or all at once with componentsJoinedByString:

NSArray *params = [NSArray arrayWithObjects:@"a",@"b",nil];
NSString *functionCall = [NSString stringWithFormat:@"showPieChart(%@)", [params componentsJoinedByString:@","]];


1) Implement the UIWebViewDelegate

2) Override the

-(BOOL)webView:(UIWebView *)aWebView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType method..

3) In this method you compare the request with a protocole defined.

Example:

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) modify your javascript file to create the protocole:

function showPieChart(parameter1,parameter2) { window.location="myapp:" + "myfunction:" + param1 + ":" + param2;

}

resouce :http://www.codingventures.com/2008/12/using-uiwebview-to-render-svg-files/


I'm guessing you have a UIWebView with a web page loaded. To execute JavaScript, do this:

NSString *result = [_webView stringByEvaluatingJavaScriptFromString:@"showPieChart()"];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜