0

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

Lets say in my html I have JS

function showPieChart (parameter1, parameter2) { ... }

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

3 Answers 3

3

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:@","]];
Sign up to request clarification or add additional context in comments.

1 Comment

Ok, that works for me...But what if my param is array ? How to send array ? Is that posible?
1

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/

Comments

0

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.