Increment app badge on recieving ACS push while app on background: Titanium - push-notification

My application uses ACS Push Notification. I have implemented app badge in my application. But the problem is the appBadge doesn't incrementing automatically while receiving a push notification. I have used the following code in my app
var deviceToken;
Titanium.Network.registerForPushNotifications({
types: [
Titanium.Network.NOTIFICATION_TYPE_BADGE,
Titanium.Network.NOTIFICATION_TYPE_ALERT,
Titanium.Network.NOTIFICATION_TYPE_SOUND
],
success:function(e)
{
deviceToken = e.deviceToken;
SubscribeToPush(channelName, deviceToken, type);
},
error:function(e)
{
alert("Error: "+ ((e.error && e.message) || JSON.stringify(e.error)));
},
callback:function(e)
{
var badgeCount = Ti.UI.iPhone.getAppBadge();
badgeCount = badgeCount + 1;
Ti.UI.iPhone.setAppBadge(badgeCount);
}
});
I read here that "callback function" invoked upon receiving a new push notification. So I set the following code as callback to increment the badge.
callback:function(e)
{
var badgeCount = Ti.UI.iPhone.getAppBadge(); //Will return the app badges
badgeCount = badgeCount + 1; //Incrementing the appbadge
Ti.UI.iPhone.setAppBadge(badgeCount); //Setting new appbadge
}
It works while the app is open and when it receives a notification, callback get fired and when the app go to background, the badge get appeared. But I want to increment the badge number when the app is in background or exited. Can anyone help me to resolve this issue?

After lots of research I have created a sample application to increment the appBadge while receiving a server push notification. You can download the code from Increment the ios appBadge Titanium. Please follow the steps after downloading the resources folder.
Create a new mobile application project in Titanium.
Replace the resources folder with the one you downloaded.
Login to www.appcelerator.com, go to your app then go to Manage ACS
Create a new user as admin, set user as admin
Create a new Access Control List(ACS) using the admin user and give the ACL Name as 'SampleApp'
Upload the p12 certificate for push notification
Now Install the application to your iPhone and run the app...
Each user of the app should have a custom object which stores the number of notifications. I'm updating them while sending a push and clears it while I resume/open the application. I tested it with my iPhone devices and it works perfect. However it takes some delays since I have to call ACS multiple times.
UPDATE : Latest Titanium SDKs Support this feature by default.
What you need to do is to change the payload as follows:
var payload = {"alert":"Hi, This is a test notification", badge: "+1"};
/*+1 will increment the current appbadge by 1, number of appbadge will be saved in the ACS*/
Cloud.PushNotifications.notify({
channel: 'friend_request',
payload: payload
}, function (e) {
if (e.success) {
alert('Success');
} else {
alert('Error:\n' +
((e.error && e.message) || JSON.stringify(e)));
}
});
And this will increase the appbadge by one. And you need to reset the appbadge when you resume/open of your application as follows
Cloud.PushNotifications.resetBadge({
device_token : myDeviceToken
}, function(e){
if(e.success){
Ti.UI.iPhone.setAppBadge(0);
} else {
//Error callback
}
})

Related

How open a specific screen show the detail of the notification in react native

How to skip/open a specific screen based notification. Example: When a user clicks on the notification, the application should open and go directly to the notifications page instead of the home page.
when i was using react-native-push-notification i mannage to get the text of my notification this way :
componentWillMount() {
var _this = this;
PushNotification.configure({
onRegister: function(token) {
_this.props.InitToken(token.token);
},
onNotification: function(notification) {
setTimeout(() => {
if(!notification['foreground']){
_this.props.InitNotif(notification['message']);
}
}, 1);
PushNotification.localNotificationSchedule({
title: 'Notification with my name',
message: notification['name'], // (required)
date: new Date(Date.now()) // in 60 secs
});
},
// ANDROID ONLY: GCM Sender ID (optional - not required for local notifications, but is need to receive remote push notifications)
senderID: "YourID",
});
}
where
_this.props.InitToken(token.token);
and
_this.props.InitNotif(notification['message']);
are redux based function that update your state with the notification token and message. When you'r state is updated whith the notification message your can change route ou display the message on screen.
PS:
i dont know if it was the good way but i was working
componentWillMount() is depreciated.

Phonegap manage notification when the app is foreground

i am building mobile application using cordova and phonegap.
I want to display a popup on device screen when the notification reaches.Is there any plugin in cordova for this.
From https://programmingistheway.wordpress.com/2017/07/19/devextremephonegap-how-to-manage-push-notifications-with-fcm/
The 3 events registration, notification and error are managed only if the app is opened.
Registration: the APP registers itself to the push service, receiving
a unique registrationId. This event is useful if you want to store
this value to send notifications to single devices;
Notification: instead of show the classic notification pop up (depending on the
phone), the event notication shows a little pop up (using DevExtreme
feature) to read the message, if the APP is open (if the app is
closed, you will get the notification in the classic way);
Error: if the APP is open and the notification throws some error, here you can manage it.
So, the event you have to mangage is notification. This event is raised when a notification is delivered with the app in foreground (so, when the app is running).
Insert this code in the deviceReady event:
var push = PushNotification.init({
android: {
},
ios: {
alert: "true",
badge: "true",
sound: "true",
clearBadge: "true"
},
windows: {}
});
push.on('registration', function (data) {
// data.registrationId
DevExpress.ui.notify("Device registered " + data.registrationId, "success", 3000);
});
push.on('notification', function (data) {
// data.message,
// data.title,
// data.count,
// data.sound,
// data.image,
// data.additionalData
// mostra la notifica se l'app è aperta
DevExpress.ui.notify(data.message, "info", 10000);
});
push.on('error', function (e) {
// e.message
// sarà da togliere, utilissimo in fase di debug
DevExpress.ui.notify(e.message, "error", 10000);
});
and insert the code you need in the notification event. In this case, DevExtreme is used, but if you don't use it you can just show an alert or look for what you need (example)enter link description here.

cordova-plugin-fcm - FCMPlugin is not defined

I am using Ionic 2, and am trying to get Push Notifications working.
I have registered my app with Firebase, and can push notifications to it successfully.
I now need to set up, so that I can push notifications from my app. So I decided to use the following Cordova Plugin (cordova-plugin-fcm).
Question 1
When I follow it's instructions, by doing the following in my Ionic app:
app.ts
declare var FCMPlugin;
...
initializeApp() {
this.platform.ready().then(() => {
...
FCMPlugin.getToken(
function (token) {
....
I get the following Error at runtime:
EXCEPTION: Error: Uncaught (in promise): ReferenceError: FCMPlugin is
not defined
How do I solve this please?
Question 2
In order to send notifications from your app, the Cordova Plugin (cordova-plugin-fcm) instructs the following:
//POST: https://fcm.googleapis.com/fcm/send
//HEADER: Content-Type: application/json
//HEADER: Authorization: key=AIzaSy*******************
{
"notification":{
"title":"Notification title", //Any value
"body":"Notification body", //Any value
"sound":"default", //If you want notification sound
"click_action":"FCM_PLUGIN_ACTIVITY", //Must be present for Android
"icon":"fcm_push_icon" //White icon Android resource
},
"data":{
"param1":"value1", //Any data to be retrieved in the notification callback
"param2":"value2"
},
"to":"/topics/topicExample", //Topic or single device
"priority":"high", //If not set, notification won't be delivered on completely closed iOS app
"restricted_package_name":"" //Optional. Set for application filtering
}
This is not even Typescript or Javascript. So where does it go? I just don't understand. Any advise appreciated.
You should have FCMPlugin.js included in your HTML index file
find the path for js file into plugins directory of the app
Example : MyFCM\plugins\cordova-plugin-fcm\www\FCMPlugin.js
app.controller('AppCtrl', function(FCMPlugin,$scope,$cordovaToast,$cordovaDialogs,ionPlatform) {
// call to register automatically upon device ready
ionPlatform.ready.then(function (device) {
console.log('I am working');
FCMPlugin.onNotification(
function(data){
if(data.wasTapped){
//Notification was received on device tray and tapped by the user.
$cordovaDialogs.alert(data.notification.body);
}else{
//Notification was received in foreground. Maybe the user needs to be notified.
$cordovaDialogs.alert(data.notification.body);
//$cordovaToast.showShortCenter( JSON.stringify(data) );
}
},
function(msg){
$cordovaToast.showShortCenter('onNotification callback successfully registered: ' + msg);
},
function(err){
$cordovaToast.showShortCenter('Error registering onNotification callback: ' + err);
}
);
});
})

push notification does not work for ios and azure with specific token

We are using Visual Studio to create an Apache Cordova app that is connected to an Azure Mobile Service . We are using the Cordova Push Plugin to receive Notifications in our app. We have created a JavaScript method in the Azure Mobile Service to send the notifications, this method is triggered by a scheduler. Please note that the intention is to send each Notification to a particular device.
The notifications work perfectly for Android devices but not for the iOS devices.
In iOS the notification is not received however the method in Azure Mobile Service always returns “Success”.
If we set the Device Token to "Null" , then it works for iOS devices (but sends to all devices not just one).
Could anyone please help us to resolve this issue?
this is Push.Send() method in Azure
push.send(result.DeviceID, payload, {
success: function(pushResponse){
//console.log("Sent push:", pushResponse);
//update notification sent time-start
var sqlUpdate = '';
mssql.query(sqlUpdate, {
success: function(results)
{
//response.json(statusCodes.OK, results);
},
error : function()
{
//response.send(statusCodes.INTERNAL_SERVER_ERROR);
}
})
//update notification sent time-end
},
error: function (pushResponse) {
//console.log("Error Sending push:", pushResponse);
}
});
and this is my App registration Method in the app
var pushNotification = window.plugins.pushNotification;
//alert("device.platform" + device.platform);
// Platform-specific registrations.
if (device.platform == 'android' || device.platform == 'Android') {
alert("device.platform : Android ");
// Register with GCM for Android apps.
pushNotification.register(
app.successHandler, app.errorHandler,
{
"senderID": GCM_SENDER_ID,
"ecb": "app.onNotificationGCM"
});
} else if (device.platform === 'iOS') {
// Register with APNS for iOS apps.
alert("device.platform : iOS ");
pushNotification.register(
app.tokenHandler,
app.errorHandler, {
"badge":"true",
"sound":"true",
"alert":"true",
"ecb": "app.onNotificationAPN"
});
}
else if(device.platform === "Win32NT"){
// Register with MPNS for WP8 apps.
alert("Device platform Windows")
pushNotification.register(
app.channelHandler,
app.errorHandler,
{
"channelName": "MyPushChannel",
"ecb": "app.onNotificationWP8",
"uccb": "app.channelHandler",
"errcb": "app.ErrorHandler"
});
}
// #endregion notifications-registration

How to make sure user in app's session and google's session are the same when using accounts-google

I am using accounts-google on my app and I'd like to solve rather odd authentication scenario.
A logs in so now as an app session and a google session
A switches to gmail and logs out there.
Now, mind you that, A is actually still logged in on the meteor app.
B comes along, logs in to Gmail using his account.
Switches to the meteor app to see that he's logged in, but oddly, logged in with A's account.
This scenario leads to lots of confusions and people unknowingly using other users' accounts where they share computers.
So, basically, I need to users in the meteor session and google session to be the same, and if not, ensure that the current meteor session is invalidated and loginWithGoogle() is called again.
How can I solve this?
It seems impossible with Meteor's current accounts package, although one could create a new one using Google's latest googleplus api.
But there seems to exist a workaround by:
1) Set up onBeforeAction hooks on your router to login the user automatically (which asks for credentials if user is not logged in to external service)
var loginWithGoogle = function() {
if (Meteor.isClient) {
Session.set('loginError', undefined);
Meteor.loginWithGoogle({
loginStyle : "redirect",
requestPermissions : ['profile', 'email'],
requestOfflineToken: true
}, function (err) {
if (err)
Session.set('loginError', 'reason: ' + err.reason + ' message: ' + err.message || 'Unknown error');
});
}
}
var requireLogin = function() {
if (! Meteor.user()) {
if (Meteor.loggingIn()) {
this.render(this.loadingTemplate);
} else {
console.log('The app is automatically asking for you to log in.');
loginWithGoogle();
}
} else {
this.next();
}
}
Router.onBeforeAction(requireLogin, {except: ['some-special-public-route']});
2) Log the user out when they are navigating away from every page (caveat: login/logout gets called everytime the user navigates within the app)
Meteor.startup(function(){
$(window).bind('beforeunload', function() {
closingWindow();
});
});
closingWindow = function(){
console.log('The app is automatically logging you out because you are leaving.');
Meteor.logout();
}
3) improvement area: set a session variable to track user's navigation within the app and run the unload event depending on the variable.

Resources