Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keep callback context in PhoneGap plugin?

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!

like image 247
boom Avatar asked Sep 12 '13 08:09

boom


2 Answers

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];
like image 88
Tony Hursh Avatar answered Oct 18 '22 01:10

Tony Hursh


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

eg

 PluginResult p3=   new PluginResult(PluginResult.Status.OK, "0");
 p3.setKeepCallback(true);
like image 2
Arjun T Raj Avatar answered Oct 18 '22 02:10

Arjun T Raj