Keep callback context in PhoneGap plugin?

て烟熏妆下的殇ゞ 提交于 2019-12-01 03:21:36

问题


I need to implement some functionality that triggers an action on an interval and emits the results back to javascript.

To simplify things I will use the echo example from the PhoneGap documentation:

- (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];

  }];
}

I want to make this call the same callback with the echo every second until stop is called.

I've created a timer that calls another function every second, but I don't know how to keep the context of the callback to send the result to.

//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");

  }];
}

Any help keeping this within the context of the callback would be great. Thanks!


回答1:


You'll want to have something like:

NSString *myCallbackId;

as an instance-level variable (outside of any method, so it retains its value). Set it when you first come in to the plugin code:

myCallbackId = command.callbackId;

Then, right after you instantiate a PluginResult, but before using it, do something like:

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

That will tell it to keep the callback valid for future use.

Then do something like:

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



回答2:


hi for getting many callback to js you can use setKeepCallback(true)

eg

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



回答3:


Just if it helps somebody, in Android I am not using PluginResult and I am still able to keep a reference to the CallbackContext and call it anytime. I am not sure if this is the right way, but I can confirm that it worked for me.



来源:https://stackoverflow.com/questions/18758756/keep-callback-context-in-phonegap-plugin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!