I'm making an app using appcelerator alloy framework which needs push notifications. I'm using push notifications for the first time, so bear with me and help me out here.
I've followed the push notification wiki tutorial here https://wiki.appcelerator.org/display/guides2/Push+Notifications
This is my code here :
var deviceToken = null;
// Check if the device is running iOS 8 or later
if (Ti.Platform.name == "iPhone OS" && parseInt(Ti.Platform.version.split(".")[0]) >= 8) {
// Wait for user settings to be registered before registering for push notifications
Ti.App.iOS.addEventListener('usernotificationsettings', function registerForPush() {
// Remove event listener once registered for push notifications
Ti.App.iOS.removeEventListener('usernotificationsettings', registerForPush);
Ti.Network.registerForPushNotifications({
success: deviceTokenSuccess,
error: deviceTokenError,
callback: receivePush
});
});
// Register notification types to use
Ti.App.iOS.registerUserNotificationSettings({
types: [
Ti.App.iOS.USER_NOTIFICATION_TYPE_ALERT,
Ti.App.iOS.USER_NOTIFICATION_TYPE_SOUND,
Ti.App.iOS.USER_NOTIFICATION_TYPE_BADGE
]
});
}
// For iOS 7 and earlier
else {
Ti.Network.registerForPushNotifications({
// Specifies which notifications to receive
types: [
Ti.Network.NOTIFICATION_TYPE_BADGE,
Ti.Network.NOTIFICATION_TYPE_ALERT,
Ti.Network.NOTIFICATION_TYPE_SOUND
],
success: deviceTokenSuccess,
error: deviceTokenError,
callback: receivePush
});
}
// Process incoming push notifications
function receivePush(e) {
alert('Received push: ' + JSON.stringify(e));
}
// Save the device token for subsequent API calls
function deviceTokenSuccess(e) {
deviceToken = e.deviceToken;
}
function deviceTokenError(e) {
alert('Failed to register for push notifications! ' + e.error);
}
// Require the Cloud module
var Cloud = require("ti.cloud");
function subscribeToChannel () {
// Subscribes the device to the 'chats' channel
// Specify the push type as either 'android' for Android or 'ios' for iOS
Cloud.PushNotifications.subscribeToken({
device_token: deviceToken,
channel:'test',
type: Ti.Platform.name == 'android' ? 'android' : 'ios'
}, function (e) {
if (e.success) {
alert('Subscribed');
} else {
alert('Error:\n' + ((e.error && e.message) || JSON.stringify(e)));
}
});
}
function unsubscribeToChannel () {
// Unsubscribes the device from the 'test' channel
Cloud.PushNotifications.unsubscribeToken({
device_token: deviceToken,
channel:'test',
}, function (e) {
if (e.success) {
alert('Unsubscribed');
} else {
alert('Error:\n' + ((e.error && e.message) || JSON.stringify(e)));
}
});
}
function loginUser(username, password){
// Log in to Arrow
Cloud.Users.login({
login: username,
password: password
}, function (e) {
if (e.success) {
subscribeToChannel ();
alert('Login successful with device token' + deviceToken);
// Store the authentication details in the local filesystem
Ti.App.Properties.setString('usernameSave',username);
Ti.App.Properties.setString('passwordSave',password);
// user_id = jsonPost.SuccessResult.user_id;
} else {
alert('Error:\n' +
((e.error && e.message) || JSON.stringify(e)));
}
});
}
var savedUserName = Ti.App.Properties.getString('usernameSave','');
var savedPassword = Ti.App.Properties.getString('passwordSave','');
if(savedUserName != ''){
$.userNameField.value = savedUserName;
$.passwordField.value = savedPassword;
}
function login(){
var username = $.userNameField.value;
var password = $.passwordField.value;
loginUser(username, password);
}
The Login() function is called when a button named login is clicked.
I get the Login Successful and Subscribed alerts as expected on login.
Whenever I tried sending a push notification to all the users, it worked. But if I try to send it to a specified user it gives me a failure on the Push Logs in the dashboard.
What am I missing here? Please help me out.
Thanks.
Ok I found the problem that was causing this.
Yeah it was my fault as in the subscription method I'm using token subscription instead of channel subscription. As I'm using the session based method.
Here is the difference, if anyone needs it in future.
Check the second line...
Previous Code
function subscribeToChannel () {
Cloud.PushNotifications.subscribeToken({
device_token: deviceToken,
channel:'test',
type: Ti.Platform.name == 'android' ? 'android' : 'ios'
}, function (e) {
if (e.success) {
alert('Subscribed');
} else {
alert('Error:\n' + ((e.error && e.message) || JSON.stringify(e)));
}
});
}
New Code
function subscribeToChannel(){
Cloud.PushNotifications.subscribe({
device_token: deviceToken,
channel: 'test',
type: Ti.Platform.name == 'android' ? 'android' : 'ios'
}, function (e) {
if (e.success) {
alert('Subscribed');
} else {
alert('Error:\n' + ((e.error && e.message) || JSON.stringify(e)));
}
});
}
Thank you.
Cheers.
Related
after a lot of investigation i have no clue of what could be the problem here. I have an iOS app developed with cordova and using Firebase (cordova-plugin-firebase) for notifications.
When i run my app on my device with Xcode for the first time everything works fine, the notifications arrive and the app works great. The problem starts when i stop the app on Xcode and try to open it on my device without using Xcode, the app crashes on the splash screen. If i send any notification, it arrives with no issue, but when i open one notification the app just crashes on the splash screen again.
I have created all certificates and the development, production and ad-hoc provisioning profiles on my apple developer account, created and APNs Key to store on my Firebase Account, I have the file GoogleService-Info.plist on my Resources folders (platforms/ios/AppName/Resources & platforms/ios/AppName/Resources/Resources).
The only error that i can see on my log is this one
Unable to connect to FCM. Error Domain=com.google.fcm Code=2001 "FIRMessaging is already connected"
and this one
The object does not respond to -messaging:didReceiveRegistrationToken:, nor -messaging:didRefreshRegistrationToken:. Please implement -messaging:didReceiveRegistrationToken: to be provided with an FCM token.
This errors are shown when i accept the notification permission bubble.
Here is my JS for handling notifications:
function firebasePUSH() {
if (device.platform === "iOS") {
window.FirebasePlugin.hasPermission(function (data) {
if (!data.isEnabled) {
window.FirebasePlugin.grantPermission();
}
});
}
window.FirebasePlugin.onNotificationOpen(function (notification) {
console.log("tipo de notificacion " + notification.tipo);
console.log(notification);
if (notification.tipo === "alerta") {
var parametros = {
id: notification.numero,
categoria: "rescato"
};
myApp.request.post("http://190.98.210.41/comuna/app/contactos.php", parametros, function (data) {
var json = JSON.parse(data);
console.log(json);
if (json.error === false) {
mostrarSOS(json.alerta);
}
});
} else if (notification.tipo === "chat" || notification.tipo === "salud" || notification.tipo === "seguridad" || notification.tipo === "contacto" || notification.tipo === "oficina") {
aceptarLlamada();
} else if (notification.tipo === "publicidad") {
mostrarPublicidad(notification.numero);
} else if (notification.tipo === "sondeo") {
mostrarSondeo(notification.numero);
}
}, function (error) {
console.error("onResume>>" + error);
});
window.FirebasePlugin.getToken(function (token) {
try {
var jsonToken = JSON.parse(token);
token = jsonToken.token;
console.warn("venia json: " + jsonToken.token);
}
catch (err) {
console.warn("viene json limpio: " + token);
}
console.log("getToken js: " + token);
localStorage.setItem('registrationId', token);
/*PEGRUNTA SI YA ESTA LOGEADO*/
if (localStorage.getItem("correo") !== null && localStorage.getItem("clave") !== null) {
//pasa a la pantalla principal
var parametros = {
"id": localStorage.getItem("id"),
"token": localStorage.getItem('registrationId'),
"categoria": "token",
format: "json",
callback: function () {
return true;
}
};
myApp.request.json("http://190.98.210.41/comuna/app/usuario_get.php", parametros, function (data) {
console.log(data);
}, function (error) {
console.log(error);
});
}
}, function (error) {
console.error("getToken error: " + error);
});
window.FirebasePlugin.onTokenRefresh(function (token) {
try {
var jsonToken = JSON.parse(token);
token = jsonToken.token;
console.warn("token json: " + jsonToken.token);
}
catch (err) {
console.warn("token limpio: " + token);
}
console.log("onTokenRefresh js: " + token);
localStorage.setItem('registrationId', token);
/*PEGRUNTA SI YA ESTA LOGEADO*/
if (localStorage.getItem("correo") != null && localStorage.getItem("clave") != null) {
//pasa a la pantalla principal
var parametros = {
"id": localStorage.getItem("id"),
"token": localStorage.getItem('registrationId'),
"categoria": "token",
format: "json",
callback: function () {
return true;
}
};
myApp.request.json("http://190.98.210.41/comuna/app/usuario_get.php", parametros, function (data) {
console.log(data);
}, function (error) {
console.log(error);
});
}
}, function (error) {
console.error(error);
});
}
I could use some help on this issue because i have been on this for weeks and i'm getting so frustrated. Thank you very much guys.
EDIT:
I spotted a third error when i launch the app.
[Firebase/Messaging][I-FCM002023] The object does not respond to -messaging:didReceiveRegistrationToken:, nor -messaging:didRefreshRegistrationToken:. Please implement -messaging:didReceiveRegistrationToken: to be provided with an FCM token.
I had a problem very similar..
and I discovered that the problem was when i called window.FirebasePlugin.grantPermission() in second time.
do one test without asking permission more than once..
I need to implement PushNotification for iOS device.
The error message this when I want to subscribe a channel
Missing fields. Required: device_token and channel
I have apple certificate and all configurations in Appcelerator dashboard.
And when I am running the app on my device app asking to confirm push notification.
I believe the error appears because of Ti.Network.registerForPushNotifications events not firing.
Here is my code.
var Cloud = require("ti.cloud");
login();
function login() {
env = Ti.App.deployType.toLowerCase() === 'production' ? 'production' : 'development',
username = Ti.App.Properties.getString('acs-username-'+env),
password = Ti.App.Properties.getString('acs-password-'+env);
// Places your already created user id credential
Cloud.Users.login({
login : username,
password : password
}, function(e) {
if (e.success) {
var user = e.users[0];
Ti.API.info(' Login Success:\n' + 'id: ' + user.id + '\n' + 'sessionId: ' + Cloud.sessionId + '\n' + 'first name: ' + user.first_name + '\n' + 'last name: ' + user.last_name);
} else {
Ti.API.info('Error:\n' + ((e.error && e.message)));
}
});
}
var deviceToken = null;
// Check if the device is running iOS 8 or later
if (Ti.Platform.name == "iPhone OS" && parseInt(Ti.Platform.version.split(".")[0]) >= 8) {
// Wait for user settings to be registered before registering for push notifications
Ti.App.iOS.addEventListener('usernotificationsettings', function registerForPush() {
Ti.App.iOS.removeEventListener('usernotificationsettings', registerForPush);
Ti.Network.registerForPushNotifications({
success : deviceTokenSuccess,
error : deviceTokenError,
callback : receivePush
});
});
Ti.App.iOS.registerUserNotificationSettings({
types : [Ti.App.iOS.USER_NOTIFICATION_TYPE_ALERT, Ti.App.iOS.USER_NOTIFICATION_TYPE_SOUND, Ti.App.iOS.USER_NOTIFICATION_TYPE_BADGE]
});
}
// For iOS 7 and earlier
else {
Ti.Network.registerForPushNotifications({
// Specifies which notifications to receive
types: [
Ti.Network.NOTIFICATION_TYPE_BADGE,
Ti.Network.NOTIFICATION_TYPE_ALERT,
Ti.Network.NOTIFICATION_TYPE_SOUND
],
success: deviceTokenSuccess,
error: deviceTokenError,
callback: receivePush
});
}
function receivePush(e) {
//Ti.API.info('Received push: ' + JSON.stringify(e));
}
function deviceTokenSuccess(e) {
deviceToken = e.deviceToken;
Ti.API.info("eeeeeeee" + e);
//subscribeToChannel();
}
function deviceTokenError(e) {
Ti.API.info('ssssssssFailed to register for push notifications! ' + e.error);
}
function subscribeToChannel () {
// Subscribes the device to the 'news_alerts' channel
// Specify the push type as either 'android' for Android or 'ios' for iOS
Cloud.PushNotifications.subscribeToken({
device_token: deviceToken,
channel: 'news_alerts',
type: Ti.Platform.name == 'android' ? 'android' : 'ios'
}, function (e) {
if (e.success) {
Ti.API.info('Subscribed');
} else {
Ti.API.info('Error:\n' + ((e.error && e.message)));
}
});
}
function unsubscribeToChannel () {
// Unsubscribes the device from the 'test' channel
Cloud.PushNotifications.unsubscribeToken({
device_token: deviceToken,
channel: 'news_alerts',
}, function (e) {
if (e.success) {
Ti.API.info('Unsubscribed');
} else {
Ti.API.info('Error:\n' + ((e.error && e.message)));
}
});
}
setTimeout(function() {
subscribeToChannel();
}, 6000);
Before making calls to Arrow DB, make sure your deviceTokenSuccessCB is getting fired and since you have indicated that it's not getting fired then you can below steps for it:
Your iOS device settings are ON for your app's notifications.
You are not using LiveView ON mode as it's a known issue here LiveView ON iOS Notification issue
I'm currently trying to make push notification working for dev/production environment through Appcelerator Platform.
I created my push certificates (dev/prod) on apple developer platform, I exported it to .p12 file, and uploaded it on my ArrowDB iOS Push configuration. My Titanium app and my ArrowDB seems correctly linked (good keys for production and developpement).
From my app, I get device token, I get a successfull return from subscribing to notifications, and I can see from Appcelerator that I have one ios device linked.
When I send push notification from Appcelerator ArrowDB platform, I don't receive anything while Appcelerator logs shows a Successful push.
My code for ACS Notification handling :
var Cloud = require('ti.cloud');
var ANDROID = Ti.Platform.name === 'android';
var IOS = !ANDROID && (Ti.Platform.name === 'iPhone OS');
var BLACKBERRY = !ANDROID && !IOS && (Ti.Platform.name === 'blackberry');
Cloud.debug = true; // optional; if you add this line, set it to false for production
var deviceToken = null;
// Check if the device is running iOS 8 or later
if (Ti.Platform.name == "iPhone OS" && parseInt(Ti.Platform.version.split(".")[0]) >= 8) {
// Wait for user settings to be registered before registering for push notifications
Ti.App.iOS.addEventListener('usernotificationsettings', function registerForPush() {
// Remove event listener once registered for push notifications
Ti.App.iOS.removeEventListener('usernotificationsettings', registerForPush);
Ti.Network.registerForPushNotifications({
success: deviceTokenSuccess,
error: deviceTokenError,
callback: receivePush
});
});
// Register notification types to use
Ti.App.iOS.registerUserNotificationSettings({
types: [
Ti.App.iOS.USER_NOTIFICATION_TYPE_ALERT,
Ti.App.iOS.USER_NOTIFICATION_TYPE_SOUND,
Ti.App.iOS.USER_NOTIFICATION_TYPE_BADGE
]
});
}
// For iOS 7 and earlier
else {
Ti.Network.registerForPushNotifications({
// Specifies which notifications to receive
types: [
Ti.Network.NOTIFICATION_TYPE_BADGE,
Ti.Network.NOTIFICATION_TYPE_ALERT,
Ti.Network.NOTIFICATION_TYPE_SOUND
],
success: deviceTokenSuccess,
error: deviceTokenError,
callback: receivePush
});
}
// Process incoming push notifications
function receivePush(e) {
console.log('Received push: ' + JSON.stringify(e));
alert('Received push: ' + JSON.stringify(e));
}
// Save the device token for subsequent API calls
function deviceTokenSuccess(e) {
deviceToken = e.deviceToken;
}
function deviceTokenError(e) {
alert('Failed to register for push notifications! ' + e.error);
}
function ACSPush(acsuid, acspwd) {
this.acsuid = acsuid || false;
this.acspwd = acspwd || false;
}
ACSPush.prototype.registerDevice = function(channel_name, onReceive, onLaunched, onFocused, androidOptions, iosOptions, blackberryOptions) {
var that = this,
token = '';
function deviceTokenSuccess(e) {
console.log('Device Token: ' + e.deviceToken);
token = e.deviceToken;
that.token = token;
loginToACS(that.acsuid, that.acspwd, token, channel_name);
}
function deviceTokenError(e) {
console.log('Token Error: ' + e.error);
}
function receivePush(e) {
onReceive(e.data);
console.log("push notification received: " + JSON.stringify(e.data));
}
if (ANDROID) {
var CloudPush = require('ti.cloudpush');
CloudPush.retrieveDeviceToken({
success : deviceTokenSuccess,
error : deviceTokenError
});
CloudPush.focusAppOnPush = androidOptions.focusAppOnPush || false;
CloudPush.showAppOnTrayClick = androidOptions.showAppOnTrayClick || false;
CloudPush.showTrayNotification = androidOptions.showTrayNotification || false;
CloudPush.showTrayNotificationsWhenFocused = androidOptions.showTrayNotificationsWhenFocused || false;
CloudPush.singleCallback = androidOptions.singleCallback || true;
CloudPush.addEventListener('callback', onReceive);
CloudPush.addEventListener('trayClickLaunchedApp', onLaunched);
CloudPush.addEventListener('trayClickFocusedApp', onFocused);
} else if (IOS) {
// Check if the device is running iOS 8 or later
if (parseInt(Ti.Platform.version.split(".")[0]) >= 8) {
function registerForPush() {
Ti.Network.registerForPushNotifications({
success : deviceTokenSuccess,
error : deviceTokenError,
callback : receivePush
});
// Remove event listener once registered for push notifications
Ti.App.iOS.removeEventListener('usernotificationsettings', registerForPush);
};
// Wait for user settings to be registered before registering for push notifications
Ti.App.iOS.addEventListener('usernotificationsettings', registerForPush);
// Register notification types to use
Ti.App.iOS.registerUserNotificationSettings({
types : iosOptions.types,
categories : iosOptions.categories
});
} else {
// For iOS 7 and earlier
Ti.Network.registerForPushNotifications({
// Specifies which notifications to receive
types : iosOptions.types,
success : deviceTokenSuccess,
error : deviceTokenError,
callback : receivePush
});
}
} else if (BLACKBERRY) {
Ti.BlackBerry.createPushService({
appId : blackberryOptions.appId,
ppgUrl : blackberryOptions.ppgUrl,
usePublicPpg : blackberryOptions.usePublicPpg,
launchApplicationOnPush : blackberryOptions.launchApplicationOnPush,
onSessionCreated : function(e) {
console.log('Session Created');
},
onChannelCreated : function(e) {
console.log('Channel Created\nMessage: ' + e.message + '\nToken: ' + e.token);
token = e.token;
that.token = token;
console.log("Device Token: " + token);
loginToACS(that.acsuid, that.acspwd, token, channel_name);
},
onPushReceived : function(e) {
onReceive(e.data);
e.source.removeAllPushes();
},
onConfigError : function(e) {
console.log('ERROR\nTitle: ' + e.errorTitle + +'\nMsg: ' + e.errorMessage);
},
onError : function(e) {
console.log('ERROR\nTitle: ' + e.errorTitle + +'\nMsg: ' + e.errorMessage);
},
onAppOpened : function(e) {
onLaunched(e.data);
e.source.removePush(e.pushId);
}
});
} else {
alert("Push notification not implemented yet into acspushmod for " + Ti.Platform.osname);
}
};
ACSPush.prototype.unsubscribeFromChannel = function(channel_name, token, onSuccess, onFail) {
var that = this;
Cloud.PushNotifications.unsubscribe({
channel : channel_name,
device_token : token
}, function(e) {
if (e.success) {
onSuccess(e);
} else {
onFail(e);
}
});
};
ACSPush.prototype.getToken = function() {
return this.token;
};
function loginToACS(acsuid, acspwd, token, channel_name) {
if (!acsuid && !acspwd) {
console.log("loginToACS -> subscribe as guest");
subscribeForPushNotifications(token, channel_name, true);
return;
}
Cloud.Users.login({
login : acsuid,
password : acspwd
}, function(e) {
if (e.success) {
var user = e.users[0];
console.log("loginToACS -> Status: Successful");
subscribeForPushNotifications(token, channel_name);
} else {
console.log('acsuid = ' + acsuid + " acspwd = " + acspwd);
console.log("loginToACS -> Error :" + e.message);
}
});
};
function subscribeForPushNotifications(token, channel_name, subscribeAsGuest) {
var prams = {
channel : channel_name,
type : IOS ? 'ios' : Ti.Platform.osname, // osname return iphone / ipad on iOS
device_token : token
};
var callBack = function(e) {
if (e.success) {
console.log('subscribeForPushNotifications -> Status: Successful [' + channel_name + ']');
} else {
console.log('subscribeForPushNotifications -> Error ' + token + '(subscribeToServerPush) :\\n' + ((e.error && e.message) || JSON.stringify(e)));
}
};
if (subscribeAsGuest) {
Cloud.PushNotifications.subscribeToken(prams, callBack);
} else {
Cloud.PushNotifications.subscribe(prams, callBack);
}
};
And This code used to work before I change appcelerator account (migrating to my client account).
If you guys have any idea of what am I doing wrong, I will be very thankful.
Thanks a lot !
Environment : Appcelerator studio, Titanium SDK 5.0.0.GA, iphone5S
4 apps in apple store and android market created with pushwoosh + phonegap build. Notifications works good on all devices except for new ios8. why? is sometheing changed? I used these 2 files:
Pushnotification.js
(function(cordova) {
function PushNotification() {}
// Call this to register for push notifications and retreive a deviceToken
PushNotification.prototype.registerDevice = function(config, success, fail) {
cordova.exec(success, fail, "PushNotification", "registerDevice", config ? [config] : []);
};
// Call this to set tags for the device
PushNotification.prototype.setTags = function(config, success, fail) {
cordova.exec(success, fail, "PushNotification", "setTags", config ? [config] : []);
};
// Call this to send geo location for the device
PushNotification.prototype.sendLocation = function(config, success, fail) {
cordova.exec(success, fail, "PushNotification", "sendLocation", config ? [config] : []);
};
PushNotification.prototype.onDeviceReady = function() {
cordova.exec(null, null, "PushNotification", "onDeviceReady", []);
};
// Call this to get tags for the device
PushNotification.prototype.getTags = function(success, fail) {
cordova.exec(success, fail, "PushNotification", "getTags", []);
};
//Android Only----
PushNotification.prototype.unregisterDevice = function(success, fail) {
cordova.exec(success, fail, "PushNotification", "unregisterDevice", []);
};
//config params: {msg:"message", seconds:30, userData:"optional"}
PushNotification.prototype.createLocalNotification = function(config, success, fail) {
cordova.exec(success, fail, "PushNotification", "createLocalNotification", config ? [config] : []);
};
PushNotification.prototype.clearLocalNotification = function() {
cordova.exec(null, null, "PushNotification", "clearLocalNotification", []);
};
//advanced background task to track device position and not drain the battery
PushNotification.prototype.startGeoPushes = function(success, fail) {
cordova.exec(success, fail, "PushNotification", "startGeoPushes", []);
};
PushNotification.prototype.stopGeoPushes = function(success, fail) {
cordova.exec(success, fail, "PushNotification", "stopGeoPushes", []);
};
//sets multi notification mode on
PushNotification.prototype.setMultiNotificationMode = function(success, fail) {
cordova.exec(success, fail, "PushNotification", "setMultiNotificationMode", []);
};
//sets single notification mode
PushNotification.prototype.setSingleNotificationMode = function(success, fail) {
cordova.exec(success, fail, "PushNotification", "setSingleNotificationMode", []);
};
//type: 0 default, 1 no sound, 2 always
PushNotification.prototype.setSoundType = function(type, success, fail) {
cordova.exec(success, fail, "PushNotification", "setSoundType", [type]);
};
//type: 0 default, 1 no vibration, 2 always
PushNotification.prototype.setVibrateType = function(type, success, fail) {
cordova.exec(success, fail, "PushNotification", "setVibrateType", [type]);
};
PushNotification.prototype.setLightScreenOnNotification = function(on, success, fail) {
cordova.exec(success, fail, "PushNotification", "setLightScreenOnNotification", [on]);
};
//set to enable led blinking when notification arrives and display is off
PushNotification.prototype.setEnableLED = function(on, success, fail) {
cordova.exec(success, fail, "PushNotification", "setEnableLED", [on]);
};
//{goal:'name', count:3} (count is optional)
PushNotification.prototype.sendGoalAchieved = function(config, success, fail) {
cordova.exec(success, fail, "PushNotification", "sendGoalAchieved", config ? [config] : []);
};
//Android End----
//iOS only----
PushNotification.prototype.startLocationTracking = function(backgroundMode, success, fail) {
cordova.exec(success, fail, "PushNotification", "startLocationTracking", backgroundMode ? [{mode : backgroundMode}] : []);
};
PushNotification.prototype.stopLocationTracking = function(success, fail) {
cordova.exec(success, fail, "PushNotification", "stopLocationTracking", []);
};
// Call this to get a detailed status of remoteNotifications
PushNotification.prototype.getRemoteNotificationStatus = function(callback) {
cordova.exec(callback, callback, "PushNotification", "getRemoteNotificationStatus", []);
};
// Call this to set the application icon badge
PushNotification.prototype.setApplicationIconBadgeNumber = function(badgeNumber, callback) {
cordova.exec(callback, callback, "PushNotification", "setApplicationIconBadgeNumber", [{badge: badgeNumber}]);
};
// Call this to clear all notifications from the notification center
PushNotification.prototype.cancelAllLocalNotifications = function(callback) {
cordova.exec(callback, callback, "PushNotification", "cancelAllLocalNotifications", []);
};
//iOS End----
// Event spawned when a notification is received while the application is active
PushNotification.prototype.notificationCallback = function(notification) {
var ev = document.createEvent('HTMLEvents');
ev.notification = notification;
ev.initEvent('push-notification', true, true, arguments);
document.dispatchEvent(ev);
};
cordova.addConstructor(function() {
if(!window.plugins) window.plugins = {};
window.plugins.pushNotification = new PushNotification();
});
})(window.cordova || window.Cordova || window.PhoneGap);
And app.js
function registerPushwooshIOS() {
var pushNotification = window.plugins.pushNotification;
//push notifications handler
document.addEventListener('push-notification', function(event) {
var notification = event.notification;
//navigator.notification.alert(notification.aps.alert);
//to view full push payload
//navigator.notification.alert(JSON.stringify(notification));
//reset badges on icon
pushNotification.setApplicationIconBadgeNumber(0);
});
pushNotification.registerDevice({alert:true, badge:true, sound:true, pw_appid:"69620-5C1D0", appname:"Maxistore"},
function(status) {
var deviceToken = status['deviceToken'];
console.warn('registerDevice: ' + deviceToken);
onPushwooshiOSInitialized(deviceToken);
},
function(status) {
console.warn('failed to register : ' + JSON.stringify(status));
navigator.notification.alert(JSON.stringify(['failed to register ', status]));
});
//reset badges on start
pushNotification.setApplicationIconBadgeNumber(0);
}
function onPushwooshiOSInitialized(pushToken)
{
var pushNotification = window.plugins.pushNotification;
//retrieve the tags for the device
pushNotification.getTags(function(tags) {
console.warn('tags for the device: ' + JSON.stringify(tags));
},
function(error) {
console.warn('get tags error: ' + JSON.stringify(error));
});
//start geo tracking. PWTrackSignificantLocationChanges - Uses GPS in foreground, Cell Triangulation in background.
pushNotification.startLocationTracking('PWTrackSignificantLocationChanges',
function() {
console.warn('Location Tracking Started');
});
}
function registerPushwooshAndroid() {
var pushNotification = window.plugins.pushNotification;
//push notifications handler
document.addEventListener('push-notification', function(event) {
var title = event.notification.title;
var userData = event.notification.userdata;
//dump custom data to the console if it exists
if(typeof(userData) != "undefined") {
console.warn('user data: ' + JSON.stringify(userData));
}
//and show alert
//navigator.notification.alert(title);
//stopping geopushes
pushNotification.stopGeoPushes();
});
//projectid: "GOOGLE_PROJECT_ID", appid : "PUSHWOOSH_APP_ID"
pushNotification.registerDevice({ projectid: "863823034249", appid : "69620-5C1D0" },
function(token) {
alert(token);
//callback when pushwoosh is ready
onPushwooshAndroidInitialized(token);
},
function(status) {
alert("failed to register: " + status);
console.warn(JSON.stringify(['failed to register ', status]));
});
}
function onPushwooshAndroidInitialized(pushToken)
{
//output the token to the console
console.warn('push token: ' + pushToken);
var pushNotification = window.plugins.pushNotification;
pushNotification.getTags(function(tags) {
console.warn('tags for the device: ' + JSON.stringify(tags));
},
function(error) {
console.warn('get tags error: ' + JSON.stringify(error));
});
//set multi notificaiton mode
//pushNotification.setMultiNotificationMode();
//pushNotification.setEnableLED(true);
//set single notification mode
//pushNotification.setSingleNotificationMode();
//disable sound and vibration
//pushNotification.setSoundType(1);
//pushNotification.setVibrateType(1);
pushNotification.setLightScreenOnNotification(false);
//goal with count
//pushNotification.sendGoalAchieved({goal:'purchase', count:3});
//goal with no count
//pushNotification.sendGoalAchieved({goal:'registration'});
//setting list tags
//pushNotification.setTags({"MyTag":["hello", "world"]});
//settings tags
pushNotification.setTags({deviceName:"hello", deviceId:10},
function(status) {
console.warn('setTags success');
},
function(status) {
console.warn('setTags failed');
});
function geolocationSuccess(position) {
pushNotification.sendLocation({lat:position.coords.latitude, lon:position.coords.longitude},
function(status) {
console.warn('sendLocation success');
},
function(status) {
console.warn('sendLocation failed');
});
};
// onError Callback receives a PositionError object
//
function geolocationError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
function getCurrentPosition() {
navigator.geolocation.getCurrentPosition(geolocationSuccess, geolocationError);
}
//greedy method to get user position every 3 second. works well for demo.
// setInterval(getCurrentPosition, 3000);
//this method just gives the position once
// navigator.geolocation.getCurrentPosition(geolocationSuccess, geolocationError);
//this method should track the user position as per Phonegap docs.
// navigator.geolocation.watchPosition(geolocationSuccess, geolocationError, { maximumAge: 3000, enableHighAccuracy: true });
//Pushwoosh Android specific method that cares for the battery
pushNotification.startGeoPushes();
}
function initPushwoosh() {
var pushNotification = window.plugins.pushNotification;
if(device.platform == "Android")
{
registerPushwooshAndroid();
pushNotification.onDeviceReady();
}
if(device.platform == "iPhone" || device.platform == "iOS")
{
registerPushwooshIOS();
pushNotification.onDeviceReady();
}
}
The push notification interface changed in iOS8. If your third-party library hasn't been updated to adapt, push notifications will likely fail.
Background:
Previously, registering for notifications was done with
-[UIApplication registerForRemoteNotificationTypes:]
As of iOS8, it is now done with:
-[UIApplication registerUserNotificationSettings:]
-[UIApplication registerForRemoteNotifications]
Take a look at the pushwoosh post
Due to multiple support requests about iOS 8 we thought itβd be good to also shed some light here in our Blog. Currently, there are two version of Pushwoosh iOS SDK:
iOS 7 SDK β must be compiled with Xcode v.5 β does not support latest features introduced in iOS 8;
iOS 8 SDK β must be compiled with Xcode v.6
So, applications compiled with iOS 7 SDK in Xcode v.5 will continue working properly on devices running iOS 8 due to its compatibility. If you use Pushwoosh iOS 8 SDK, you must compile your app with Xcode v.6.
You can download it here
The pushPlugin.register function is getting called for Android, but not iOS. Here is the code I have.
this.initialize is getting called and I see the first alert there -- alert('PushNotifications:initialize');
Any ideas? why pushPlugin.register and window.onNotificationAPN function don't seem to get called?. At one brief point it was working, IIRC. I'm not sure what changed.
Here's my config setup:
https://gist.github.com/adaptivedev/d33f38cd3d6cf10be9dc
Thanks!
.service('PushNotifications', function(Utility, $cordovaToast, $rootScope) {
alert('PushNotifications');
var pushPlugin = null;
/*
this.deviceRegId = function() {
$rootScope.getFDeviceId();
}
*/
this.initialize = function() {
alert('PushNotifications:initialize');
document.addEventListener('deviceready', function() {
//alert('PushNotifications:initialize:deviceready:device='+JSON.stringify(device));
pushPlugin = window.plugins.pushNotification;
if ( device.platform == 'android' || device.platform == 'Android' || device.platform == "amazon-fireos" ){
pushPlugin.register(
function(result) {
console.log('PushNotifications:initialize:1:result='+result);
},
function(result) {
alert('PushNotifications:initialize:2:result='+result);
console.log(JSON.stringify(result));
},
{
"senderID":"123",
"ecb":"onNotificationGCM"
});
} else {
pushPlugin.register(
function(result) {
alert('PushNotifications:initialize:1:result='+result);
//$rootScope.setDeviceId(result)
},
function(result) {
alert('PushNotifications:initialize:2:result='+result);
console.log(JSON.stringify(result));
},
{
"badge":"true",
"sound":"true",
"alert":"true",
"ecb":"onNotificationAPN"
});
}
});
// notifications for Android
window.onNotificationGCM = function(e) {
alert('onNotificationGCM:e='+JSON.stringify(e));
window.boosterNotification = e;
switch( e.event )
{
case 'registered':
if ( e.regid.length > 0 )
{
$rootScope.setDeviceId(e.regid);
}
break;
case 'message':
// if this flag is set, this notification happened while we were in the foreground.
// you might want to play a sound to get the user's attention, throw up a dialog, etc.
if ( e.foreground )
{
// on Android soundname is outside the payload.
// On Amazon FireOS all custom attributes are contained within payload
var soundfile = e.soundname || e.payload.sound;
// if the notification contains a soundname, play it.
//var my_media = new Media("/android_asset/www/"+ soundfile);
//my_media.play();
}
else
{ // otherwise we were launched because the user touched a notification in the notification tray.
if ( e.coldstart )
{
//
}
else
{
//
}
}
var msg = e.payload.message.replace(/<b>/g, "")
msg = msg.replace(/<\/b>/g, "");
$cordovaToast.showShortCenter(msg).then(function(success) {
//$state.go('app.upcoming');
$rootScope.updateNotifications();
}, function (error) {
// error
}
);
//alert(e.payload.message);
//Only works for GCM
// e.payload.msgcnt + '</li>');
//Only works on Amazon Fire OS
// e.payload.timeStamp
break;
case 'error':
//e.msg
break;
default:
// Unknown
break;
}
};
// notifications for iOS
window.onNotificationAPN = function(result) {
alert('onNotificationAPN:result:1:='+JSON.stringify(result));
if ( event.alert )
{
//navigator.notification.alert(event.alert);
}
if ( event.sound )
{
//var snd = new Media(event.sound);
//snd.play();
}
if ( event.badge )
{
//.setApplicationIconBadgeNumber(successHandler, errorHandler, event.badge);
}
console.log('onNotificationAPN:result='+JSON.stringify(result));
window.boosterNotification = result;
};
};
});
I solved it! In Xcode, select the file (PushPlugin.m) and on right side check "Target Membership"