Ios Phonegap Simple Plugin

You have a Phonegap project, up and running and you want to create a simple plugin.

On your Plugins directory create two files

SimplePlugin.h which contains these lines

#import <Cordova/CDVPlugin.h>
@interface SimplePlugin : CDVPlugin
-(void)sayHello:(CDVInvokedUrlCommand*)command;
@end

and SimplePlugin.c which contains these lines

#import "SimplePlugin.h"

/**
* Gkatziouras Emmanouil 
* Simple phonegap Plugin
*/

@implementation SimplePlugin

-(void)sayHello:(CDVInvokedUrlCommand *)command {
    
    CDVPluginResult* pluginResult = nil;
    NSString* javascript = nil;
   
    //You can choose other statuses for the result such as CDVCommandStatus_ERROR CDVCommandStatus_NO_RESULT and more
    pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:@"Hello From Phonegap"];
    
    javascript = [pluginResult toSuccessCallbackString:command.callbackId];
    [self writeJavascript:javascript];
}
@end

Now on your javascript file you can call the native code through the Cordova.exec function

Cordova.exec(
                 function(success_parameters) {alert(success_parameters);},
                 function(error_parameters){alert(error_parameters)},
                 "SimplePlugin",
                 "sayHello",
                 ["noparameters"]
                 );

The bad news is that you only have the choice to make async calls to the native code you created.
The first parameter of the function is when the plugin is succesfully called, this means that you used the CDVCommandStatus_OK to send a result. The second parameter is a function when it comes to use the CDVCommandStatus_ERROR status on your native code. The third parameter is the plugin’s name, the forth is the function you want to call. The last parameter is the json data you want to pass to your native function.

Also don’t forget to register your plugin at the Cordova.plist file.

   <dict>
   <key>SimplePlugin</key>
   <string>SimplePlugin</string>
   </dict>
Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.