Search code examples
ioscordovacordova-plugins

Keep listener for iOS Cordova plugin variable changes


I'm building an iOS Cordova plugin, in this plugin i have a variable that is always changing values. When i call this plugin method that returns this variable from js, I want it to stay active and always get the new changed value from Objective-c.

This is my code:

/**
 *This method will return the Volume of the user's speech ( It can be used as a UI feedback)
 */
- (void) getRecognitionVolume:(CDVInvokedUrlCommand*)command
{
    CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:[NSString stringWithFormat:@"%1.6f", volumeLevel]];

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

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

js code:

getVolumeBtn.addEventListener('click', function() {

                                    cordova.exec(
                                                 function successCallback(data) {
                                                 volumeDiv.innerHTML ="Volume: "+ data;
                                                 },
                                                 function errorCallback(err) {
                                                 alert('Error');
                                                 },
                                                 'VoiceControl',
                                                 'getRecognitionVolume',
                                                 []
                                                 );
                                    });

So to conclude I want the volumeDiv to always hold the new volume value.

Any help would be appreciated.


Solution

  • The problem was that I didn't fully understand the way setKeepCallback works: I thought if set to true it will automatically keep the method running and sending the new value whenever the variable changes.

    The way I have to use it is whenever the value changes I must send the result again.

    Here's where I pass the result now: (this is the handler that's always called when the volume changes in my code)

    - (void) pollVolume
    {
       [self getRecognitionVolume:volumeCommand];
    
    }