Reputation: 61
I'm trying to integrate push notifications into my Ionic/Cordova app. I'm using a service OneSignal for integration. I have successfully set up my iPhone to receive push notifications from OneSignal's web interface.
The next step is to get the pushToken (which OneSignal/Apple uses to send push notifications to a single device) to populate in my app's ionic controller so that I can implement application logic and push messages based on app events.
I installed their (OneSignal's) Cordova plugin and my iPhone registers and it reports the pushToken. However I cannot pass the pushToken string to any of my controllers for the life of me. How can I do this? Below is my app.js and controller.js.
app.js
angular.module('cApp', ['ionic', 'cApp.controllers'])
.run(function($ionicPlatform, $cordovaSplashscreen, $rootScope) {
$ionicPlatform.ready(function() {
if(window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
cordova.plugins.Keyboard.disableScroll(true); // Fixes keyboard issue
}
if (window.StatusBar) {
// org.apache.cordova.statusbar required
StatusBar.styleDefault();
}
/*===========================================================================
http://documentation.onesignal.com/v2.0/docs/phonegap--cordova-sdk-api#init
===========================================================================*/
window.plugins.OneSignal.init("5eb87dse-b458-11e3-ac11-000c2940e62c",
{googleProjectNumber: "",
autoRegister: true},
app.didReceiveRemoteNotificationCallBack);
window.plugins.OneSignal.getIds(function(ids) {
console.log('getIds: ' + JSON.stringify(ids)); // I can see PushToken and UserId in the console.
$rootScope.pushToken = ids.pushToken;
});
});
console.log($rootScope.pushToken);
})
// Configure Routes....... etc.
controller.js
.controller('MenuCtrl', function($scope, $rootScope, $ionicModal, $ionicPlatform) {
console.log($rootScope.pushToken); // It comes back undefined :(
Upvotes: 3
Views: 1867
Reputation: 3948
It sounds like app.js runs before your controller.js. If this is the case you should be able to do the following;
Here is the code implementing these 2 flows:
app.js:
didReceiveRemoteNotificationCallBack(message, additionalData, isActive) {
var notificationObj = {message: message, additionalData: additionalData, isActive: isActive};
if ($rootScope.notificationReceivedHandler)
$rootScope.notificationReceivedHandler(notificationObj);
else
$rootScope.openedFromNotification = notificationObj;
}
controller.js:
.controller('MenuCtrl', function($scope, $rootScope, $ionicModal, $ionicPlatform) {
if ($rootScope.openedFromNotification)
processNotificationOpened($rootScope.openedFromNotification);
$rootScope.openedFromNotification = processNotificationOpened;
}
function processNotificationOpened(notificationObj) {
// Read and process what you need to here.
}
NOTE: The code above is not tested.
Upvotes: 1