I am dealing with a problem with IONIC and FCM. It is the following, I am sending "data" not "notifications" from my server in Node JS to my app in IONIC, I see in the console that the data is sent, but I don't know how to access it, according to the documentation, it is in Intent extras, but I have not had success with it. I could use the "notifications" that also serve me, but the problem with that is that only if you click on the push notification do you get the data ... so if the client does not click on the notification and enters the app from the background will not be able to get that data ...
My server in Node:
const options = {
priority: "high",
timeToLive: 60 * 60 * 24,
};
const message_notification = {
/*
notification: {
title: "¡Tienes un nuevo pedido!",
body: "Tienes 30 segundos para aceptar el pedido, de lo contrario será rechazado.",
sound: "default",
vibrate: 1,
Badge: 1,
click_action: "FCM_PLUGIN_ACTIVITY"
},
*/
data: {
detalles: JSON.stringify(nuevopedido)
},
};
admin
.messaging()
.sendToDevice(primeroCola.socket_id, message_notification, options)
.then((response) => {
console.log("Notificación enviada", response);
})
.catch((error) => {
console.log(error);
});
My app in ionic:
this.fcm.onNotification().subscribe((data) => {
console.log(JSON.parse(data.detalles))
});
I tried with the cordova intent web plugin in Ionic, but I can't get the FCM intent, just my project in ionic, I don't really know much about Android.
WebIntent.getIntent().then((intent) => {
console.log('Action' + JSON.stringify(intent.action));
const intentExtras = intent.extras;
if (intentExtras == null) {
console.log("No hay extras")
} else {
console.log('Extras de intent: ' + JSON.stringify(intentExtras));
}
}, (error) => {
console.log('Error getting launch intent', error);
});
Add this before of FCMPlugin.sendPushPayload(data); in onMessageReceived (file: MyFirebaseMessagingService):
FCMPlugin.setInitialPushPayload(data);
It happens that when you only send "data" without "notification" in FCM, it does not make a set of the payload (FCMPlugin.setInitialPushPayload(data)), because there is nothing to tapped, there is no notification and it cannot listen to the "notification" event because the app is closed, so there is to get the data when you open the application again (when the app is closed) in some way, then setting that when using the getInitialPushPayload in your app, you will get the data:
App in ionic:
async created() {
const payload = await this.fcm.getInitialPushPayload()
console.log(payload)
},
Now, when you open your application that was closed, you will receive the data.
Related
I have an Ionic 5 app with Capacitor 3 and I'm trying to receive notifications using Firebase Cloud messaging, on an Android device. I followed the configurations,(I downloaded the google JSON file and put my app id name correctly ) and I'm getting correctly the device token. Once my app is open I get the token successfully without any error and then I send a notification sharing my token to the Firebase test message, the notification never arrived, and also I never get an error of push notification in my logger. This is the code that I use for push notification.
export class PushNotificationsService {
constructor(private readonly http: HttpClient, private notificationState: NotificationsStore) { }
public initPush() {
if (Capacitor.getPlatform() !== 'web') {
this.registerPush();
}
}
private registerPush() {
PushNotifications.requestPermissions().then(async result => {
if (result.receive === 'granted') {
// Register with Apple / Google to receive push via APNS/FCM
console.log('granted');
await PushNotifications.register();
} else {
// Show some error
console.log('errorr');
}
});
// On success, we should be able to receive notifications
PushNotifications.addListener('registration',
(token: Token) => { (I get through this step and access the token successfully)
console.log('Push registration success, token: ' + token.value);
this.notification state.setToken(token.value);
}
);
// I never get this step error
PushNotifications.addListener('registrationError',
(error: any) => {
console.log('Error on registration: ' + JSON.stringify(error));
}
);
PushNotifications.addListener('pushNotificationReceived',
(notification: PushNotificationSchema) => {
console.log('Push received: ' + JSON.stringify(notification));
}
);
PushNotifications.addListener('pushNotificationActionPerformed',
(notification: ActionPerformed) => {
console.log('Push action performed: ' + JSON.stringify(notification));
}
);
}
I also have capacitor.config.json like this:
"PushNotifications": {
"presentationOptions": ["badge", "sound", "alert"]
}
Also, I checked that my device and app have permission for notifications and are enabled both. I tried and test this issue with my app open and closed and open only in the background and the notification never arrives. What it could be? Any clue? Thank you
Android Phone Please Create the channel Like this, Test or Add screenshot for console Error
if (Capacitor.getPlatform() === 'android') {
PushNotifications.createChannel({
id: 'fcm_default_channel',
name: 'app name',
description: 'Show the notification if the app is open on your device',
importance: 5,
visibility: 1,
lights: true,
vibration: true,
});
}
Unfortunately, no answer yet. I am checking out postman, I hope I can use that to test quicker.
I manage to send a notification through my app, however, the notification always ends up in the silent notification of my phone, no sound, no vibration and no notification icon in the top left of the phone, only a notification in the drawer when I swipe down :(
In an attempt to fix / improve the situation I tried the following:
Create an android notification channel with id: high_importance_channel by using flutter_local_notifications package. The channel was created successful, because requesting an overview of the existing channels, showed the newly created channel (among the other channels). The new channel has importance: 5, enableVibration: true and playSound: true, so that should do the job.
Send a FCM through cloud functions with the following code:
const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp();
exports.chatNotification = functions.firestore
.document('chats/{groupId}/chat/{chatId}')
.onCreate( async (snapshot, context) => {
const message = {
"notification": {
"title": "Message Received",
"body": "Text Message from " + fromUserName,
},
"tokens": registrationTokens,
"android": {
"notification": {
"channel_id": "high_importance_channel",
},
},
};
admin.messaging().sendMulticast(message)
.then((response) => {
console.log(response.successCount + ' messages were sent successfully');
});
}
But so far not luck, the notification still ends up in the silent notifications. What am I doing wrong?
There are 2 ways of doing it. Might work in your case.
Way 1:
var payload = {
notification: {
android_channel_id: 'AppChannel',
/*
https://stackoverflow.com/questions/62663537/how-do-i-add-a-channelid-to-my-notification
https://firebase.google.com/docs/cloud-messaging/http-server-ref#notification-payload-support
*/
title: 'Push Notification Arrived!',
body: 'Using Cloud Functions',
sound: 'default',
},
data: {
route: '/someRoute',
},
};
try {
const response = await admin.messaging().
sendToDevice(deviceTokens, payload);
console.log('Notification sent succesfully.');
} catch (err) {
console.log('Error sending Notifications...');
console.log(err);
}
Way 2:
const message = {
/*
https://firebase.google.com/docs/reference/admin/node/firebase-admin.messaging.basemessage.md#basemessagenotification
*/
notification: {
title: 'Push Notification Arrived!',
body: 'Using Cloud Functions',
},
data: {
route: '/someRoute',
},
android: {
/*
https://firebase.google.com/docs/reference/admin/node/firebase-admin.messaging.androidnotification.md#androidnotificationbodylockey
*/
notification: {
channelId: "AppChannel",
priority: 'max',
defaultSound: 'true',
},
},
token: deviceTokens,
};
// https://firebase.google.com/docs/reference/admin/node/firebase-admin.messaging.messaging.md#messagingsend
admin.messaging().send(message)
.then((response) => {
// Response is a message ID string.
console.log('Successfully sent message:', response);
})
.catch((error) => {
console.log('Error sending message, for LOVEs sake:', error);
});
I have a code that prepares and sends a notification to a mobile application
// Create the notification
const payload = {
notification: {
title: "Title",
body: "Body",
},
};
// Options
const options = {
contentAvailable: true,
priority: 'high'
};
admin
.messaging()
.sendToDevice(tokenSnapshot, payload, options)
.then(response => {
console.warn(">> Notification sent successfully: ", response);
return response;
})
.catch(error => {
console.warn(">> Notification sent failed: ", error);
});
I would like to add here information such as:
priority: 'max'
visibility: 'public'
These are features supported in Android
It is mentioned in the documentation that it exists.
But there is nothing mentioned how to use it
Can anyone give advice?
The purpose of this is to display Notifications on your phone when it is in the background
I'm implementing Push Notifications on my Android Ionic 2 App with the Ionic Native FCM
When I'm receiving a notification in the foreground it works, but when I'm receiving a notification in the background and if I clicked on it, nothing happens.
app.component.ts
firebaseInit(){
//Firebase
this.fcm.subscribeToTopic('all');
this.fcm.getToken()
.then(token => {
console.log(token);
this.nativeStorage.setItem('fcm-token', token);
});
this.fcm.onNotification().subscribe(
data => {
console.log("NOTIF DATA: " + JSON.stringify(data));
if(data.wasTapped){
this.nav.push(MemoViewPage, {memo: {_id: data.memo_id}})
console.info('Received in bg')
}else{
let alert = this.alertCtrl.create({
title: data.subject,
message: "New memorandum",
buttons: [
{
text: 'Ignore',
role: 'cancel'
},
{
text: 'View',
handler: () => {
this.nav.push(MemoViewPage, {memo: {_id: data.memo_id}})
}
}
]
});
alert.present();
console.info('Received in fg')
}
});
this.fcm.onTokenRefresh()
.subscribe(token => {
console.log(token);
})
}
The if(data.wasTapped) condition doesn't go off once I clicked the notification from the system tray.
EDIT
The app opens but only in the Home Page not to the designated page that I set which is this.nav.push(MemoViewPage, {memo: {_id: data.memo_id}})
I also cannot receive notifications when the app is killed or not running.
you could use push plugin instead of FCM.
this.push.createChannel({
id: "testchannel1",
description: "My first test channel",
importance: 3
}).then(() => console.log('Channel created'));
and then you could use pushObjects to specify the needs for your notification like sound, ion etc.
const options: PushOptions = {
android: {},
ios: {
alert: 'true',
badge: true,
sound: 'false'
},
windows: {},
browser: {
pushServiceURL: 'http://push.api.phonegap.com/v1/push'
}
};
After that it is easy for you to receive notifications whether you are using the app or not
const pushObject: PushObject = this.push.init(options);
pushObject.on('registration').subscribe((registration: any) => this.nativeStorage.setItem('fcm-token', token));
pushObject.on('notification').subscribe((notification: any) => console.log('Received a notification', notification));
you could use the option of forceShow:true in the pushObject init for the app to show the notification whether you are using the app or not.
And once you clicked the notification the notification payload is received by the app with the app home page set as default.
I have setup a Mobile Service in Azure and connected it to my Android app. Through this app I am calling the Azure API to insert an object into a database table linked to the mobile service.
I have written the script that is executed before it gets inserted. That script is intended to send a push notification to another device.
Now the case is, the object gets inserted into table but no push notification is received. What could be wrong? How can i debug?
Here's my insert script:
function insert(item, user, request) {
var devices = tables.getTable('Devices');
var receiverHandle;
devices.where({userId: item.receiver}).read({
success: populateHandle
});
request.execute({
success: function() {
// Write to the response and then send the notification in the background
request.respond();
console.log(item);
push.gcm.send(item.handle, item, {
success: function(response) {
console.log('Push notification sent: ', response);
}, error: function(error) {
console.log('Error sending push notification: ', error);
}
});
}
});
function populateHandle(results){
receiverHandle = results[0].handle;
}
}
Although logs state successful delivery of push notification. I am not receiving it on my device.
Here is one of the logs:
Push notification sent: { isSuccessful: true, statusCode: 201, body: '', headers: { 'transfer-encoding': 'chunked', 'content-type': 'application/xml; charset=utf-8', server: 'Microsoft-HTTPAPI/2.0', date: 'Sun, 10 Aug 2014 15:01:52 GMT' }, md5: undefined }
Refer to Migrate a Mobile Service to use Notification Hubs.
Microsoft had been upgraded the Mobile Service, to push notifications powered by Notification Hubs. You will not be affected if you created the mobile service before the upgrade.
Base on the response { isSuccessful: true, statusCode: 201, body ... }, it indicate that your Mobile Service is the new version.
If you prefer to send push without Notification Hubs, don't use push.gcm.send, use the following code snippet instead.
var legacyGcm = require('dpush');
legacyGcm.send(your_GCM_APIKEY, regId, item, function (error, response) {
if (!error) {
// success code
} else {
// error handling
}
});