Similar question here: jQueryMobile, Phonegap and Device Token - iOS
The scenario is, I have this PhoneGap web based application, and the native iOS help me registered t
For the sake of completeness, this is my solution after using @TDeBailleul solution. Ported over to Cordova. (Tested on iOS only. After I have finished Android version I will post a plugin for this:
Environment
Working Flow
AppDelegate
, and to get the token, use the PushToken
in the following codesSo below is my complete working codes that do the native pulling of token. Server part is nothing but just linking accounts to devices. You should know how to do it through your favourite server side application.
AppDelegate.h
@interface AppDelegate : NSObject < UIApplicationDelegate, UIWebViewDelegate, CDVCommandDelegate > {
...
NSString* token;
...
}
...
...
...
@property (retain, nonatomic) NSString* token;
AppDelegate.m
Note: I'm a Obj-C newbie and I have included my attempt to post token to my server as well. If you do not need the posting mechanism, retain the first 5 lines (til' self.token = dt
) in the didRegisterForRemoteNotificationsWithDeviceToken
...
@synthesize token;
...
- (BOOL) application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions
{
...
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:
(UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)];
return YES;
}
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
NSLog(@"Did finish launching with device token %@", deviceToken);
NSString *dt = [[deviceToken description] stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];
dt = [dt stringByReplacingOccurrencesOfString:@" " withString:@""];
self.token = dt;
NSString *dv = [[UIDevice currentDevice] systemVersion];
NSString *dn = [[UIDevice currentDevice] systemName];
NSString *nick = [[UIDevice currentDevice] name];
NSString *model = [[UIDevice currentDevice] model];
NSString *uniqueIdentifier = [[UIDevice currentDevice] uniqueIdentifier];
NSMutableString *postData = [NSMutableString stringWithString: @"&deviceToken="];
[postData appendString:dt];
[postData appendFormat:@"&uniqueIdentifier=%@&application_uuid=5ade8400-e29c-41d4-a716-3641972a2ec6", uniqueIdentifier];
[postData appendFormat:@"&source=ios&name=%@&model=%@&systemName=%@&systemVersion=%@", nick, model, dn, dv];
NSString* escapedURLString = [postData stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
@try {
NSData *postData = [escapedURLString dataUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]
initWithURL: [NSURL URLWithString:@"{YOUR URL TO POST TOKEN TO SERVER}"]
cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval: 180];
NSString *postLength = [[NSString alloc] initWithFormat: @"%d", [postData length]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (conn) {
//??
}else{
//??
}
}
@catch (NSException *exception) {
NSLog(@"Exception %@", exception);
}
}
...
PushToken.h
#import
#import
@interface PushToken : CDVPlugin {
NSString* callbackID;
}
@property (nonatomic, copy) NSString* callbackID;
- (void) getToken:(NSMutableArray*)arguments withDict:(NSMutableDictionary*)options;
@end
PushToken.m
#import "PushToken.h"
#import "AppDelegate.h"
@implementation PushToken
@synthesize callbackID;
- (void)getToken:(NSMutableArray *)arguments withDict:(NSMutableDictionary *)options {
NSLog(@"Did called getToken");
self.callbackID = [arguments pop];
NSString *token = ((AppDelegate *)[[UIApplication sharedApplication] delegate]).token;
CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:[token stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
if (token.length != 0) {
[self writeJavascript: [pluginResult toSuccessCallbackString:self.callbackID]];
}else{
[self writeJavascript: [pluginResult toErrorCallbackString:self.callbackID]];
}
}
@end
PushToken.js
var PushToken = {
/**
* Get token from the device
* @param {array} types - By default is ['getToken']
* @param {function} success Success callback, with token
* @param {function} fail Failure callback, with null
*/
getToken: function(types, success, fail) {
return Cordova.exec(success, fail, "PushToken", "getToken", types);
},
/**
* For the sake of iOS, we need an install function
*/
install: function() {
window.plugins = window.plugins || {};
window.plugins.PushToken = PushToken;
}
};
/**
* For the rest of the devices
*/
window.plugins = window.plugins || {};
window.plugins.PushToken = PushToken;
Usage
document.addEventListener('deviceready', function() {
if (typeof PushToken == 'object') {
PushToken.install();
}
PushToken.getToken(['getToken'], function(token) {
callback(token);
}, function() {
callback(null);
});
});
And you should be able to get your token from your Javascript side ;)
Have fun!
Cheers