Usando push notifications con Ionic

René A. Morales
Código Banana: El blog de Platanus
3 min readApr 21, 2015

Utilizando ngCordova junto con el plugin $cordovaPush tenemos mucho trabajo hecho para utilizar notificaciones Push de Google y Apple. Pero igual hay cierto trabajo que queda hacerlo en nuestras apps.

En este blog post, propongo un pequeño servicio para hacer la vida un poquito más facil. El servicio maneja la parte del registro y persistencia del token de Push en LocalStorage.

Requerimientos

Aparte de tener instalado ngCordova, tendremos que usar el fork platanus/PushNotifications

ionic plugin add https://github.com/platanus/PushNotification.git

PushNotifications Service

Este servicio encapsula el trabajo de $cordovaPush y provee un par de funciones

APIs públicas

  • PushNotifications.ensureRegistration: Registra la applicación con Google GCM o Apple APN si es necesario y guarda los tokens(Registration ID o Device ID). Este metodo debe llamarse siempre que se quieren recibir notificaciones Push, no solo para registrar la primera vez. El plugin PushNotification (nuestro fork), ya mantiene un control de estado de registro. En GCM se registrará únicamente la primera vez y cuando se actualice la versión de la App.
  • PushNotifications.getToken: Devuelve el device Token o GCM ID
  • PushNotifications.onMessage: Funcion que es llamada en cada mensaje push recibida

Ejemplo implementado en app.js

// We depend on ngCordova. app.env is just a helper to get ENV variables
angular.module('starter', ['app.env', 'ngCordova'])
.run(function(PushNotifications) {
ionic.Platform.ready(function() {// This is just needed for Android GCM, on IOS would be ignored
PushNotifications.setGcmSenderId('XXX');
PushNotifications
.ensureRegistration()
.onMessage(function(message) {
console.log("New push notification", message);
});
});
});
https://gist.github.com/emilioeduardob/01e4a8fa9088dfd7e4ba?file=app.jsensureRegistration puede recibir dos callbacks de success y errorPushNotifications.setGcmSenderId('XXX');
PushNotifications.ensureRegistration(function(regInfo) {
console.log("Registrado!", regInfo.source, regInfo.token);
}, function() {
console.log("Error al registrar");
});
Mensajes en AndroidPushPlugin generará notificaciones si el payload del mensaje recibido contiene ciertos atributos:
- message es usado para establecer el texto de la notificación.
- sound el nombre del archivo a reproducir(sin extension en Android.). El sonido debe ser guardado en platforms/android/res/raw/cool_sound.wav
- smallIcon el nombre del icono para la notificación (sin extension en Android.). Si smallIcon no existe, el plugin busca un icono llamado ic_stat_notify y si no existe utiliza el icono de la app
- title establece el titulo (Generalmente el nombre de la App)
- msgcnt (opcional) agrega un numero al costado inferior derecho de la notificación.
El plugin tambien agrega otro atributo al mensaje. coldstart, que ayuda a determinar si al tocar la notificación, la app se inicio o ya estaba abierta. Este atributo se agrega al mensaje recibido en el callback de onMessage{
"coldstart":"true",
"foreground":"0",
"payload": {
"message":"Mi mensaje genial",
"msgcnt":"3",
"title": "App Title or Whatever",
"sound": "cool_sound",
"smallIcon": "my_custom_icon"
}
}
Mensajes en iOSEn iOS las notificaciones las crea el propio sistema. El mensaje que se recibe es diferente al de Android, puesto que los atributos enviados no vienen dentro de un objeto payload:{"sound":"default","alert":"Mi mensaje genial","hello":"world","foreground":"0"}Los datos enviados en iOS no vienen dentro de un payloadangular.module("utils")
.factory("PushNotifications", function($cordovaPush, $rootScope){
var msgCallback;
var regCallback;
var errorCallback;
var gcmSenderId;
var service = {
setGcmSenderId: setGcmSenderId,
ensureRegistration: ensureRegistration,
getToken: getToken,
onMessage: onMessage
}
return service;function setToken(token) {
window.localStorage.setItem('pushToken', token);
}
function setGcmSenderId(senderId) {
gcmSenderId = senderId;
}
function getToken() {
return window.localStorage.getItem('pushToken', '');
}
function onMessage(cb) {
msgCallback = cb;
}
// returns an object to the callback with source and token properties
function ensureRegistration(cb, errorCb) {
regCallback = cb;
errorCallback = errorCb;
document.addEventListener("deviceready", function(){
if (ionic.Platform.isAndroid()) {
registerAndroid();
$rootScope.$on('$cordovaPush:notificationReceived', androidPushReceived);
}
if (ionic.Platform.isIOS()) {
registerIOS();
$rootScope.$on('$cordovaPush:notificationReceived', iosPushReceived);
}
});
return this;
}
function registerIOS() {
var config = {
"badge": true,
"sound": true,
"alert": true,
};
$cordovaPush.register(config).then(function(result) {
setToken(result.deviceToken);
if (regCallback !== undefined) {
regCallback({
source: 'ios',
token: result.deviceToken
});
}
}, function(err) {
if (errorCallback !== undefined) {
errorCallback(err);
}
console.log("Registration error on IOS: ", err)
});
}// Inits the Android registration
// NOTICE: This will not set the token inmediatly, it will come
// on the androidPushReceived
function registerAndroid() {
var config = {
"senderID": gcmSenderId
};
// PushPlugin's telerik only register if necesary or when upgrading app
$cordovaPush.register(config).then(function(result) {
console.log("Registration requested!");
}, function(err) {
console.log("Error registering on Android", err);
});
}// Process incoming push messages from android
function androidPushReceived(event, notification) {
switch(notification.event) {
case 'registered':
if (notification.regid.length > 0 ) {
setToken(notification.regid);
if (regCallback !== undefined) {
regCallback({
source: 'android',
token: notification.regid
})
}
}
break;
case 'message':
if (msgCallback !== undefined) { msgCallback(notification) }
break;
case 'error':
console.log('GCM error = ' + notification.msg);
break;
default:
console.log('An unknown GCM event has occurred');
break;
};
}
function iosPushReceived(event, notification) {
if (msgCallback !== undefined) { msgCallback(notification) }
}
});https://gist.github.com/emilioeduardob/01e4a8fa9088dfd7e4ba?file=PushNotifications.js

--

--