uiWebview call javascript function syntax

ios, iphone, javascript, xcode

Solution

As per this answer on another similar question, you need to implement the `UIWebView` delegate method `webViewDidFinishLoad:`, and in there implement `[myWebView stringByEvaluatingJavaScriptFromString:@"myJavaScriptCode()"]`.

In order for this to work you need to set the delegate on the `UIWebView` instance and implement the delegate method mentioned above so that the JavaScript is executed after the page has loaded.

The documentation for `- (NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)script` can be found here.

Now for the other part of your question (thanks for clarifying!).. to concatenate strings in Objective-C you can use the `NSString` class method `stringWithFormat:`.

For example, to pass two Objective-C values to a JavaScript string, you could do something like this:

// Substitute your Objective-C values into the string
NSString *javaScript = [NSString stringWithFormat:@"setVars('%@', '%@')", var1, var2, nil];

// Make the UIWebView method call
NSString *response = [webViewA stringByEvaluatingJavaScriptFromString:javaScript];

Problem

I am migrating my app from android to iOS and for following line, compiler returns me an error on iOS, `webviewA.loadUrl("javascript:setVars(\"" + var1 + "\",\"" + var2 + "\")");` //properly executed on Android for iOS I am trying, ``` [webViewA stringByEvaluatingJavaScriptFromString:@"javascript:setVars(\"" + var1 + "\",\"" + var2 + "\")"]; ``` which would be correct syntax for iOS? Thank you.

Original source

Related problems