Keep callback context in PhoneGap plugin?

I need to implement some functions that trigger an action on an interval and return the results in 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 this call to invoke the same callback with an echo every second until stop is called.

I created a timer that calls a different function every second, but I don’t know how to save the callback context to send the result.

 //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 supporting this in a callback context would be great. Thanks!

+4
source share
3 answers

You need to have something like:

 NSString *myCallbackId; 

as an instance level variable (outside of any method, so it retains its value). Install it when you first enter the plugin code:

 myCallbackId = command.callbackId; 

Then, immediately after creating the PluginResult instance, but before using it, do the following:

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

This will say that it will support a callback for future use.

Then do something like:

 [self.commandDelegate sendPluginResult:pluginResult callbackId:myCallbackId]; 
+5
source

hi to get a lot of callbacks for js you can use setKeepCallback (true)

eg

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

Just if this helps someone, in Android I don't use PluginResult, and I can still save the CallbackContext link and call it anytime. I'm not sure if this is the right way, but I can confirm that it worked for me.

0
source

Source: https://habr.com/ru/post/1501792/


All Articles