我有一些从我的本机代码生成的值,我想传递给phonegap.这些数据是实时生成的,并不直接受用户通过phonegap gui操作的影响.我的本机代码是我制作的插件的一部分.
解决这个问题的最佳方法是什么?我希望有一个函数可以随时发送数据,并在cordova端有一个监听器.我正在使用Cordova 1.5和Xcode 4.3.
这是我到目前为止:
swipe.js:
var swipe={
callNativeFunction: function (success,fail,resultType) {
return Cordova.exec( success,"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> ...
swipe.h:
... @interface swipe : CDVPlugin - (void) nativeFunction:(NSMutableArray*)arguments withDict:(NSMutableDictionary*)options; @end
swipe.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中设置代码.
解决方法
听起来你需要能够从目标C回到PhoneGap,在这种情况下你应该可以使用类似的东西:
Nsstring *jsResult = [theWebView stringByEvaluatingJavaScriptFromString:@"hello()"]; NSLog(@"jsResult=%@",jsResult);
如果你的index.html中有一个类似“hello”的JS函数,就像这样:
function hello(){return "hello";}
它是一种回复PhoneGap网络层的方式