将Javascript变量传递给Objective

将Javascript变量传递给Objective

本文介绍了将Javascript变量传递给Objective-C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在这里看到了如何将Objective-C变量传递给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.

这篇关于将Javascript变量传递给Objective-C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 15:18