iOS Cordova: Does Cordova create multiple instances of an objective-C plugin when called more than once?

时光总嘲笑我的痴心妄想 提交于 2020-01-16 01:12:08

问题


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:


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.



来源:https://stackoverflow.com/questions/32139534/ios-cordova-does-cordova-create-multiple-instances-of-an-objective-c-plugin-whe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!