我有一些从我的 native 代码生成的值,我想将它们传递给 phonegap。这些数据是实时生成的,不会直接受到用户通过 phonegap gui 的操作的影响。我的 native 代码是我制作的插件的一部分。
解决这个问题的最佳方法是什么?我想要一个功能来随时发送数据并在 cordova 端有一个监听器。我在 Xcode 4.3 中使用 Cordova 1.5。
这是我目前所拥有的:
滑动.js:
var swipe={
callNativeFunction: function (success, fail, resultType) {
return Cordova.exec( success, fail,
"ca.swipe",
"nativeFunction",
[resultType]); }
};
index.html:
...
function callNativePlugin( returnSuccess ) {
swipe.callNativeFunction( nativePluginResultHandler, nativePluginErrorHandler, returnSuccess );
}
function nativePluginResultHandler (result) {
alert("SUCCESS: \r\n"+result );
}
function nativePluginErrorHandler (error) {
alert("ERROR: \r\n"+error );
} ... <body onload="onBodyLoad()"> <h1>Hey, it's Cordova!</h1>
<button onclick="callNativePlugin('success');">Success</button>
<button onclick="callNativePlugin('error');">Fail</button>
</body> ...
滑动.h:
...
@interface swipe : CDVPlugin
- (void) nativeFunction:(NSMutableArray*)arguments withDict:(NSMutableDictionary*)options;
@end
滑动.m:
...
- (void) nativeFunction:(NSMutableArray*)arguments withDict:(NSMutableDictionary*)options {
NSLog(@"Hello, this is a native function called from PhoneGap/Cordova!");
//get the callback id
NSString *callbackId = [arguments pop];
NSString *resultType = [arguments objectAtIndex:0];
NSMutableArray *GlobalArg=arguments;
CDVPluginResult *result;
if ( [resultType isEqualToString:@"success"] ) {
result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString: @"Success :)"];
//writes back the smiley face to phone gap.
[self writeJavascript:[result toSuccessCallbackString:callbackId]];
}
...
我现在拥有的代码无法执行我想要的操作。我不太确定如何在 cordova 和 native 中设置代码。
最佳答案
听起来您需要能够从 objective-c 返回到 PhoneGap,在这种情况下您应该能够使用类似的东西:
NSString *jsResult = [theWebView stringByEvaluatingJavaScriptFromString:@"hello()"];
NSLog(@"jsResult=%@",jsResult);
如果你的 index.html 中有一个像“hello”这样的 JS 函数,就像这样:
function hello(){return "hello";}
这是一种与您的 PhoneGap 网络层对话的方式
关于ios - 将值从 iOS native 代码传递到 cordova,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11655936/