I'm having troubles trying to register my GCM regid with ngCordova and $cordovaPush.
I can't manage to retrieve my regid inside my controller to send it to my API via $http:
var gcmToken;
gcmNotificationHandler = function(e) {
if (e.event === "registered") {
gcmToken = e.regid;
console.log(gcmToken);
}
};
var aTonAvis = angular.module('aTonAvis', ['ngCordova']);
aTonAvis.value('serverUrl', "http://atonavis.local/");
aTonAvis.controller('RegisterCtrl', function($scope, $cordovaPush,
$cordovaDevice, $http, serverUrl) {
var gcmConfig = {
"senderID": "00000000000"
};
var iosConfig = {
"badge": "true",
"sound": "true",
"alert": "true",
};
gcmConfig.ecb = "gcmNotificationHandler";
iosConfig.ecb = "iosNotificationHandler";
var configHandler = function() {
if ($cordovaDevice.getPlatform().toLowerCase() ===
'android' || $cordovaDevice.getPlatform() ===
'amazon-fireos') {
return gcmConfig;
} else {
return iosConfig;
}
};
this.registered = false;
document.addEventListener("deviceready", function onDeviceReady() {
$cordovaPush.register(configHandler()).then(function(
result) {
console.log("Inside register " + gcmToken);
var pushToken;
if ($cordovaDevice.getPlatform().toLowerCase() ===
'ios') pushToken = result;
else pushToken = gcmToken;
$http.post(serverUrl + 'api/setdevice', {
token: pushToken,
device: $cordovaDevice.getPlatform(),
version: $cordovaDevice.getVersion(),
model: $cordovaDevice.getModel()
}).success(function(data, status,
headers, config) {
this.registered = true;
});
}, function(err) {
console.log("Registering Error : " + err);
});
});
});
The .then function is fired before the gcmNotificationHandler so my gcmToken is undefined, and here's what I get in my logs :
Inside register : undefined app.js:41
APA91bEzVUk3T1T6WpIsEHOq43hCh_pZeBPjRDPSPxV2j6VjVW-KcUepbmf6snaCiqGvYp3H_XYHIXQdbVtvMF3t-NtoZJaJzV9FkNtUlutuWYs5XPAZ-H1ixQnAyhTO6fAPDMn7Ef5f5HgBR9fgWpmXc0u_xBM4yKvoXCnVXEG18IZV2hvY app.js:6
I don't know what I'm doing wrong here, can anybody help ?
You need to install these two cordova plugins before run the app.
Device cordova plugin: https://github.com/apache/cordova-plugin-device
Console cordova plugin: https://github.com/apache/cordova-plugin-console
http://blog.revivalx.com/2014/11/14/implement-push-notifications-for-android-and-ios-phonegap-part-3/