I wanted to offer my solution (based off of Adam Ware's solution).
Normally I don't like just giving all the code for people to copy and paste, but I feel like this is a bit of an exception as a lot of people diving into PhoneGap know nothing about Objective-C and its funny-looking syntax (like me).
So here's what I went through using the code and following the guide Adam pointed to:
In my project plugin folder at <project name>/Plugins/
, I created MyCDVPlugin.m
and MyCDVPlugin.h
.
I've written in C before, so I understand headers, but for those of you that don't, it's basically telling the complier what to look for, so we just tell it the name of our method and import Cordova's header:
#import <Cordova/CDVPlugin.h>
@interface MyCDVPlugin : CDVPlugin
- (void)getVersionNumber:(NSMutableArray*)arguments withDict:(NSMutableDictionary*)options;
@end
Those parameters are the standard Cordova plugin parameters (as far as I know). Our function, as a getter, doesn't actually have any parameters in one sense, but those are still required. (options
might actually be optional? I didn't test.)
In our .m
, all we need is the actual function, our header from before, and CDVPluginResult.h
:
#import "MyCDVPlugin.h"
#import <Cordova/CDVPluginResult.h>
@implementation MyCDVPlugin
- (void)getVersionNumber:(NSMutableArray*)arguments withDict:(NSMutableDictionary*)options {
NSString* version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"];
NSString* callbackId = [arguments objectAtIndex:0];
CDVPluginResult* pluginResult = nil;
NSString* javaScript = nil;
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:version];
javaScript = [pluginResult toSuccessCallbackString:callbackId];
[self writeJavascript:javaScript];
}
@end
Basically, this gets the version number and passes it back to your success callback. (I didn't think this method really has a fail case, so it doesn't have a fail callback.)
For completeness' sake, Xcode doesn't auto-update files (which actually makes sense), but I always forget. Just because your files are in your project directory, doesn't mean they're in your project. Don't forget to drag them into your Plugins directory in your project:
Also, make sure you add your plugin to your Cordova.plist Plugins
entry:
From there, it's pretty simple to call the method from JavaScript (make sure to use it after deviceready
is triggered):
// get and show the version number
var gotVersionNumber = function(version) {
// cache value so we can use it later if we need it
Hub.Global.Version = version;
$('.version-number').text(version);
};
// my plugin doesn't even have a failure callback, so we pass null.
// 5th param (parameters to pass into our Obj-C method) is NOT
// optional. must be at least empty array
cordova.exec(gotVersionNumber, null, "MyCDVPlugin", "getVersionNumber", []);
That's it! Simple, right...? Hope this helps someone else a little overwhelmed by the Obj-C side of PhoneGap.