问题描述
我正在开发基于Cordova的iOS混合应用程序。我们有一个Objective-C插件文件(MyPlugin.h和MyPlugin.m),该文件通常是CDVPlugin的子类。
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.
我们从如下所示的JavaScript文件中调用Objective-C插件。
We call the objective-C plugin from a JavaScript file like below.
cordova.exec(success, error, "MyPlugin", "callNativeActivity", args);
此处,成功-成功回调函数,
error-错误回调函数
和 args-个参数数组。
Here, success- success callback function,error- error callback functionand args- array of arguments.
以下是本机插件方法签名
Below is the native plugin method signature.
-(void)callNativeActivity:(CDVInvokedUrlCommand *)cdvCommand;
我们正在插件类内部异步启动NSURLConnection任务。因此,它将等待响应来自Web服务器。响应到达后,我们将其作为CDVPluginResult对象发送回JavaScript。
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];
}
在少数情况下,我们需要同时多次调用该插件从JavaScript中获取(无需等待插件类的响应)。
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).
如果多次调用Cordova,它将如何处理。它会弄乱我发回JavaScript的响应吗?我知道Cordova具有用于发送插件结果的独特回调ID。但是,我的回复是否有可能发送到错误的实例?
希望我的问题很清楚!!任何建议将不胜感激。
Hope my question is clear!! Any suggestions will be appreciated.
推荐答案
从规格:
每个CordovaApp / WebView仅有一个插件实例。
This means, there is only one instance of a plugin per CordovaApp/WebView.
回调由ID正确处理。
它的工作原理像 这样(不确定真正的实现):
It works like this (not sure about the real implementation):
- 每次调用
cordova.exec(...)
会生成一个回调ID。 - 应用程序映射到callback [ID] = {成功,错误}
- 您的本机代码调用onSuccess(ID),将调用成功
- 调用onSuccess或onError之后,callback [ID]为设置为null
- 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
在现实世界中,也可以有某种进度侦听器,但它们也应使用正确的回调-ID。
In the real world, there can also be some kind of progress listeners, but they should also work with the correct callback-ID.
这篇关于iOS Cordova:当多次调用Cordova时,它们会创建一个Objective-C插件的多个实例吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!