我有一些从我的本机代码生成的值,我想传递给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]];
- }
- ...