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