3

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.

Jaume
  • 3,672
  • 19
  • 60
  • 119
  • for people who want an elegant demo on the topic of Javascript run in UIWebview, please refer to :http://creiapp.blogspot.hk/2013/04/uiwebview-javascript.html – Cullen SUN Apr 18 '13 at 05:43

1 Answers1

9

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];
Community
  • 1
  • 1
jstr
  • 1,271
  • 10
  • 17
  • I am asking for script! I am properly making javascript calls with a single var but how to do it with two as explained? Thanks – Jaume Aug 12 '12 at 11:31
  • Whoops, your question was a bit vague but thanks for clarifying. I've updated my answer with details :) – jstr Aug 12 '12 at 11:41