将Javascript变量传递给Objective-C

问题描述:

我已经在这里看到了如何将Objective-C变量传递给JavaScript,将目标c变量传递给ios中的javascript ,但是当我使用这样的东西时,如何将变量从JavaScript传递给Objective-C:

I've seen how to pass an Objective-C variable to JavaScript right here, passing objective c variable to javascript in ios, but how do I pass a variable from JavaScript to Objective-C when I'm using something like this:

[webView stringByEvaluatingJavaScriptFromString:@var elems = document.body.getElementsByTagName(\u\);
passThisVarToObjC = elems.length;

嗯,这就是我们的意思拨打字符串键入

Well, this is what we call stringly typed.

因为 stringByEvaluatingJavaScriptFromString:的返回类型是 NSString * ,您将需要坚持使用字符串或将值强制转换为其他(读取:更可用的)类型。

Because the return type of stringByEvaluatingJavaScriptFromString: is NSString *, you will either need to stick to using a string or coercing the value into some other (read:more usable) type.

但无论如何, stringByEvaluatingJavaScriptFromString:会毫无问题地返回JavaScript变量的值。

But anyway, stringByEvaluatingJavaScriptFromString: will return the value of a JavaScript variable to you without a problem.

这样做的方法是使用匿名函数(在这种情况下是自动执行):

The way this is accomplished is through the use of an anonymous function (which in this case is self-executing):

NSString *numOfElements = [webView stringByEvaluatingJavaScriptFromString:@"(function() {var elems = document.body.getElementsByTagName(\"u\"); return elems.length;})();"];

//do normal stuff with numOfElements like cast to an int or something cool like that.