将值从iOS本机代码传递给cordova

前端之家收集整理的这篇文章主要介绍了将值从iOS本机代码传递给cordova前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一些从我的本机代码生成的值,我想传递给phonegap.这些数据是实时生成的,并不直接受用户通过phonegap gui操作的影响.我的本机代码是我制作的插件的一部分.

解决这个问题的最佳方法是什么?我希望有一个函数可以随时发送数据,并在cordova端有一个监听器.我正在使用Cordova 1.5和Xcode 4.3.

这是我到目前为止:

swipe.js:

  1. var swipe={
  2. callNativeFunction: function (success,fail,resultType) {
  3. return Cordova.exec( success,"ca.swipe","nativeFunction",[resultType]); }
  4.  
  5. };

index.html的:

  1. ...
  2.  
  3. function callNativePlugin( returnSuccess ) {
  4. swipe.callNativeFunction( nativePluginResultHandler,nativePluginErrorHandler,returnSuccess );
  5. }
  6.  
  7. function nativePluginResultHandler (result) {
  8. alert("SUCCESS: \r\n"+result );
  9. }
  10.  
  11. function nativePluginErrorHandler (error) {
  12. alert("ERROR: \r\n"+error );
  13. } ... <body onload="onBodyLoad()"> <h1>Hey,it's Cordova!</h1>
  14.  
  15. <button onclick="callNativePlugin('success');">Success</button>
  16. <button onclick="callNativePlugin('error');">Fail</button>
  17.  
  18. </body> ...

swipe.h:

  1. ...
  2. @interface swipe : CDVPlugin
  3. - (void) nativeFunction:(NSMutableArray*)arguments withDict:(NSMutableDictionary*)options;
  4. @end

swipe.m:

  1. ...
  2. - (void) nativeFunction:(NSMutableArray*)arguments withDict:(NSMutableDictionary*)options {
  3.  
  4. NSLog(@"Hello,this is a native function called from PhoneGap/Cordova!");
  5.  
  6. //get the callback id
  7. NSString *callbackId = [arguments pop];
  8. NSString *resultType = [arguments objectAtIndex:0];
  9. NSMutableArray *GlobalArg=arguments;
  10.  
  11. CDVPluginResult *result;
  12. if ( [resultType isEqualToString:@"success"] ) {
  13. result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString: @"Success :)"];
  14. //writes back the smiley face to phone gap.
  15. [self writeJavascript:[result toSuccessCallbackString:callbackId]];
  16. }
  17.  
  18. ...

我现在的代码没有做我想做的事情.我真的不确定如何在cordova和native中设置代码.

解决方法

听起来你需要能够从目标C回到PhoneGap,在这种情况下你应该可以使用类似的东西:
  1. NSString *jsResult = [theWebView stringByEvaluatingJavaScriptFromString:@"hello()"];
  2. NSLog(@"jsResult=%@",jsResult);

如果你的index.html中有一个类似“hello”的JS函数,就像这样:

  1. function hello(){return "hello";}

它是一种回复PhoneGap网络层的方式

猜你在找的iOS相关文章