Reputation: 991
In my case, I wanna build a simple plugin which:
I did not found the way to handle the callback. I searched the cordova doc(the Echo example), the first part is quite straightforward. However, it does not mention the async callback.
Upvotes: 0
Views: 1108
Reputation: 30356
You can send an async response by sending a "no result" response synchronously and preserving the Cordova callback in order to send the asynchrous result with it. For example:
Android:
public class MyPlugin extends CordovaPlugin {
private static CallbackContext myAsyncCallbackContext = null;
@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
if (action.equals("myAsyncFunction")) {
// save the callback context
someCallbackContext = myAsyncCallbackContext;
// Send no result for synchronous callback
PluginResult pluginresult = new PluginResult(PluginResult.Status.NO_RESULT);
pluginresult.setKeepCallback(true);
callbackContext.sendPluginResult(pluginresult);
}
return true;
}
// Some async callback
public void onSomeAsyncResult(String someResult) {
if(myAsyncCallbackContext != null){
// Send async result
myAsyncCallbackContext.success(someResult);
myAsyncCallbackContext = null;
}
}
}
iOS:
@interface MyPlugin : CDVPlugin
- (void)myAsyncFunction:(CDVInvokedUrlCommand *)command;
@end
@implementation MyPlugin
static NSString* myAsyncCallbackId = nil;
- (void)myAsyncFunction:(CDVInvokedUrlCommand *)command {
// save the id
myAsyncCallbackId = command.callbackId;
// Send no result for synchronous callback
CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_NO_RESULT];
[pluginResult setKeepCallbackAsBool:YES];
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}
// Some async callback
- (void) didReceiveSomeAsyncResult:(NSString *)someResult {
if(myAsyncCallbackId != nil){
// Send async result
CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:someResult];
[self.commandDelegate sendPluginResult:pluginResult callbackId:myAsyncCallbackId];
myAsyncCallbackId = nil;
}
}
@end
Upvotes: 3