在PhoneGap插件中保留回调上下文?

时间:2013-09-12 08:04:42

标签: cordova phonegap-plugins cordova-3

我需要实现一些能够触发间隔操作的功能,并将结果发送回javascript。

为简化起见,我将使用PhoneGap文档中的echo示例:

- (void)echo:(CDVInvokedUrlCommand*)command
{
  [self.commandDelegate runInBackground:^{

    CDVPluginResult* pluginResult = nil;
    NSString* echo = [command.arguments objectAtIndex:0];

    if (echo != nil && [echo length] > 0) {
        pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:echo];
    } else {
        pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR];
    }

    [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];

  }];
}

在调用stop之前,我希望每秒都使用回显相同的回调。

我已经创建了一个每秒调用另一个函数的计时器,但我不知道如何保持回调的上下文以将结果发送到。

//Starts Timer
- (void)start:(CDVInvokedUrlCommand*)command
{
  [NSTimer scheduledTimerWithTimeInterval:1.0
                                  target:self
                                  selector:@selector(action:)
                                  userInfo:nil
                                  repeats:YES];
}

//Called Action
-(void)action:(CDVInvokedUrlCommand*)command
{
  [self.commandDelegate runInBackground:^{

    NSLog(@"TRIGGERED");

  }];
}

在回调的上下文中保持这一点的任何帮助都会很棒。谢谢!

3 个答案:

答案 0 :(得分:9)

你想要的东西是:

NSString *myCallbackId;

作为实例级变量(在任何方法之外,因此它保留其值)。首次进入插件代码时设置它:

myCallbackId = command.callbackId;

然后,在您实例化PluginResult之后,但在使用它之前,请执行以下操作:

[pluginResult setKeepCallback:[NSNumber numberWithBool:YES]];

这将告诉它保持回调有效以备将来使用。

然后执行以下操作:

[self.commandDelegate sendPluginResult:pluginResult callbackId:myCallbackId];

答案 1 :(得分:1)

您可以使用 setKeepCallback(true)

来获取js的回调

例如

 PluginResult p3=   new PluginResult(PluginResult.Status.OK, "0");
 p3.setKeepCallback(true);

答案 2 :(得分:0)

如果它对某人有帮助,在Android中我没有使用PluginResult,我仍然能够保持对CallbackContext的引用并随时调用它。我不确定这是否正确,但我可以确认它对我有用。