简体   繁体   中英

Pass variables from Objective-C to javascript function?

I have a simple javascript function that takes two variables. I need to pass two variables that I already have in my Objective-C (iOS) application to this javascript function. My line of code to run the javascript is:

[webView stringByEvaluatingJavaScriptFromString:@"onScan()"];

The javascript function just applies the two variables to a HTML form and submits it. I'm of course getting undefined in my form since the variables are missing. 8-) I've been unable to find much documentation on this, but maybe I'm looking in the wrong places?

FWIW, my Objective-C variables are strings. My javascript function is onscan(a,b)

UPDATE:

I was able to get this working by placing single quotes around each of the variables being passed to the javascript function. The updated code is:

[webView stringByEvaluatingJavaScriptFromString:@"onScan('%@','%@')",a,b];

stringByEvaluatingJavaScriptFromString: takes an NSString so all you have to do is combine strings using stringWithFormat: and the %@ object formatter like below:

NSString *stringOne = @"first_parameter";
NSString *stringTwo = @"second_parameter";

NSString *javascriptString = [NSString stringWithFormat:@"onScan('%@','%@')", stringOne, stringTwo];

[webView stringByEvaluatingJavaScriptFromString:javascriptString];

Check out Apple's documentation for NSString , it's an insanely useful object!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM