iOS Cordova: Does Cordova create multiple instance

2019-08-09 02:46发布

I am working on a iOS hybrid application based on Cordova. We have a Objective-C plugin file (MyPlugin.h and MyPlugin.m) which is typically a subclass of CDVPlugin.

We call the objective-C plugin from a JavaScript file like below.

cordova.exec(success, error, "MyPlugin", "callNativeActivity", args);

Here, success- success callback function, error- error callback function and args- array of arguments.

Below is the native plugin method signature.

-(void)callNativeActivity:(CDVInvokedUrlCommand *)cdvCommand;

We are initiating a NSURLConnection task asynchronously inside the plugin class. So, it will wait for the response to come from web server. After the response comes, we send it back to JavaScript as a CDVPluginResult object.

if (isSuccess) {

        CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:jsonPayload];
        [self.commandDelegate sendPluginResult:result callbackId:cdvCommand.callbackId];

}else{            
        CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:jsonPayload];
        [self.commandDelegate sendPluginResult:result callbackId:cdvCommand.callbackId];
}

There are few cases, wherein we need to call the plugin more than once simultaneously from JavaScript (without waiting for the response from plugin class).

How does Cordova handles if we call it multiple times. Will it mess up with the response which I send back to JavaScript? I know that Cordova has distinct callback ID for sending the plugin result. But, is there any chance of my response being sent to wrong instance?

Hope my question is clear!! Any suggestions will be appreciated.

1条回答
孤傲高冷的网名
2楼-- · 2019-08-09 03:19

From the specs Plugin Initialization and Lifetime:

One instance of a plugin object is created for the life of each UIWebView. Plugins are ordinarily instantiated when first referenced by a call from JavaScript. Otherwise they can be instantiated by setting a param named onload to true in the config.xml file.

This means, there is only one instance of a plugin per CordovaApp/WebView.

The callbacks are handled properly, by the ID.

It works like this (not sure about the real implementation):

  • Each time you call cordova.exec(...) a callback-ID is generated.
  • The application maps to callback[ID]= {success, error}
  • Your native code calls onSuccess(ID) and the success will be called
  • After calling onSuccess or onError, the callback[ID] is set to null

In the real world, there can also be some kind of progress listeners, but they should also work with the correct callback-ID.

查看更多
登录 后发表回答