How to send push notification to all the users via firebase cloud functions? - ios

Previously I send the push notification using FCM token of the devices for particular user using admin.messaging().sendToDevice(tokens, payload).
Now I'm trying to send the push notification to all the users. But it's not working. Here is my implementation. Is this correct? If wrong how to achieve my task?
const payload = {
notification: {
title: 'Hey! 💛',
body: `Check Choice of the day.`,
sound: 'default',
icon: '',
type: 'Editorial',
badge : '1'
}
};
return admin.messaging().sendToTopic("News",payload)
.then(function(response){
console.log('Notification sent successfully:',response);
})
.catch(function(error){
console.log('Notification sent failed:',error);
});

Related

Push Notification Not Received In IOS Firebase Cloud Functions

Push notifications are working as expected in the android application however nothing is received in IOS. Test notifications are also being received in IOS successfully.
const payload = {
data: {
'key': 'value'
}
};
admin.messaging().sendToDevice(notificationToken, payload)
For anyone stuck on this IOS requires notification to be included so your payload should have the following structure:
const payload = {
notification: {
'title': 'value',
'body': 'value'
},
data: {
'key': 'value'
}
};
admin.messaging().sendToDevice(notificationToken, payload)

Nativescript | Firebase notification not working

I'm having a problem using firebase in my Nativescript application, when I'm using android its working great but not working with IOS. the problem is on message sending.
I'm using the push-plugin in the client side
This is the register part in the IOS client side using pushPlugin
const iosSettings:any = {
badge: true,
sound: true,
alert: true,
interactiveSettings: {
actions: [{
identifier: 'READ_IDENTIFIER',
title: 'Read',
activationMode: "foreground",
destructive: false,
authenticationRequired: true
}, {
identifier: 'CANCEL_IDENTIFIER',
title: 'Cancel',
activationMode: "foreground",
destructive: true,
authenticationRequired: true
}],
categories: [{
identifier: 'READ_CATEGORY',
actionsForDefaultContext: ['READ_IDENTIFIER', 'CANCEL_IDENTIFIER'],
actionsForMinimalContext: ['READ_IDENTIFIER', 'CANCEL_IDENTIFIER']
}]
},
notificationCallbackIOS: (message: any) => {
alert(JSON.stringify(message));
}
};
pushPlugin.register(iosSettings, (token: string) => {
// update the token in the server
alert("Device registered. Access token: " + token);
});
}
}, (errorMessage: any) => {
alert("Device NOT registered! " + JSON.stringify(errorMessage));
});
This is how i receive my token to the push notification,
after a got the token when i'm using the pusher application everything works great, i'm getting the notification in the IOS device
but the problem is when im trying to send the notification from the server!.
I get this error :
Invalid registration token provided. Make sure it matches the
registration token the client app receives from registering with FCM.
Node code in my server
var payload = {
data: {
targetId:userToken,
body: "some text"
}
};
var options = {
priority: "high",
contentAvailable: true,
timeToLive: 60 * 60 * 24
};
Admin.messaging().sendToDevice(userToken, <any>payload,options)
.then((response) => {
console.log('notification arrived successfully', response.results[0]);
})
.catch((error) => {
console.log('notification failed', error);
});
registration token for ios is not the same for android. I encountered the same wall you've encountered. You need to use https://github.com/node-apn/node-apn for IOS push notification. and firebase for android notification. You can do the logic on your backend by saving the token. with a field called type which is ios or android if ios you use node-apn and if android use sendToDevice provided by firebase.
Thats what i'm currently using with my current nativescript projects' I'm working on that involves push notification. Hope that helps you, mate.

Can I send a silent push notification from a Firebase cloud function?

Is it possible to send a silent APNs (iOS) remote notification from a Firebase Cloud Function? If so, how can this be done? I want to send data to iOS app instances when the app is not in the foreground, without the user seeing a notification.
I currently send a notification that can be seen by users:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendNotifications = functions.database.ref('/events/{pushId}').onWrite(event => {
const id = event.params.pushId
const payload = {
notification: {
title: 'An event has occurred!',
body: 'Please respond to this event.',
event_id: id
}
};
return admin.messaging().sendToTopic("events", payload);
});
I would like to be able to send that id to the app without a visual notification.
I figured out how to modify my code to successfully send a silent notification. My problem was that I kept trying to put content_available in the payload, when it really should be in options. This is my new code:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendNotifications = functions.database.ref('/events/{pushId}').onWrite(event => {
const id = event.params.pushId
const payload = {
data: {
title: 'An event has occurred!',
body: 'Please respond to this event.',
event_id: id
}
};
const options = {
content_available: true
}
return admin.messaging().sendToTopic("events", payload, options);
});
I successfully received the silent notification on my iOS device after implementing application:didReceiveRemoteNotification:fetchCompletionHandler and userNotificationCenter:willPresent:withCompletionHandler.
If you're talking about APNs notifications, the answer is: No, you can't send a notification without visualisation. You can only disable a sound. But, you can passed an FCM Data message without visualisation. You can read about it here: https://firebase.google.com/docs/cloud-messaging/concept-options
{
"to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
"data" : {
"Nick" : "Mario",
"body" : "great match!",
"Room" : "PortugalVSDenmark"
}
}

is there any way to send different badge count to different users in a same topic?

I have FCM integration in my Node.js project where I am sending number of notifications to the IOS users and I need to manage notification count i.e. Badge count which will be different across the devices but I am sending notification to a particular topic to which these devices are subscribed.
my Payload is :
var payload = {
notification: {
title: "Title...",
body: "Notification Body...",
sound: "customeSound.caf",
badge : "?"
},
data: {
testData: "custom data"
}
},
topic = "topicName";
admin.messaging().sendToTopic(topic, payload)
.then(function (response) {
// See the MessagingTopicResponse reference documentation for the
// contents of response.
console.log("Successfully sent message:", response);
})
.catch(function (error) {
console.log("Error sending message:", error);
});
});
All devices that are subscribed to the corresponding topic will receive the same payload you set.
You'll have to send a separate payload for each device. Or if applicable, maybe just group the ones with the similar badge value -- but that would require you to send to a group of tokens (using registration_ids) instead of sending to a topic.
If you have the devices tokens and you want to send the badge counts to respective device token,
Instead of sending them one by one ( Which I personally think is not a good idea) the best alternative you can do is:-
You can achieve this by doing something like.....
First of all you need to query your DB to get the device token and badge count respectively
So say like you have and array
const badgeCounts = [{
device_token:'aaaaaaaaaaaaaaaaaaaaaa',
badge_count: 1
},{
device_token:'bbbbbbbbbbbbbbbbbbbbbb',
badge_count: 2
},{
device_token:'cccccccccccccccccccccc',
badge_count: 3
},{
device_token:'dddddddddddddddddddddd',
badge_count: 4
}]
Now you can map over this array and compose array of fcm messages, something like below :-
const fcmMessages = [];
badgeCounts.forEach((data) => {
fcmMessages.push({
token: data.device_token, //device token
apns: {
payload: {
aps: {
alert: {
title: "your title",
body: "your body",
},
badge: data.badge_count, // badge
contentAvailable: true,
},
},
},
data: {
// any payload goes here...
},
notification: {
title: "your title",
body: "your body",
},
});
});
/// in firebase messiging you can do like
messaging.sendAll(fcmMessages);
refer doc https://firebase.google.com/docs/reference/admin/node/admin.messaging.Messaging-1#sendall

Firebase Cloud Messaging push notification not being sent to device

This is what my log looks like when my push notification gets called on
I am currently working on creating push notification set up for a user to user setting for the iPhone. I am currently using Firebase, so naturally I turned to Firebase Cloud Messaging to get this done. This is my setup in the functions that I am deploying to my Firebase. Is there something that I am doing wrong in here that would result in the notification not being sent to the device? I appreciate any help, and if there is any more needed information I would be happy to supply it.
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
// Listens for new messages added to messages/:pushId
exports.pushNotification = functions.database.ref('/messages/{pushId}').onWrite( event => {
console.log('Push notification event triggered');
// Grab the current value of what was written to the Realtime Database.
var valueObject = event.data.val();
console.log(valueObject)
if(valueObject.photoUrl != null) {
valueObject.photoUrl= "Sent you a photo!";
}
// Create a notification
const payload = {
notification: {
title:valueObject.toId,
body: valueObject.text || valueObject.photoUrl,
sound: "default"
},
};
//Create an options object that contains the time to live for the notification and the priority
const options = {
priority: "high",
timeToLive: 60 * 60 * 24
};
return admin.messaging().sendToTopic("pushNotifications", payload, options);
if(!data.changed()){
});
exports.pushNotification = functions.database.ref('/messages/{pushId}').onWrite( event => {
const data = event.data;
console.log('Push notification event triggered');
return;
}
});
I noticed that you are exposing the same function twice. That is also an issue. Also I suggest you to promisify the admin.messaging, so that you can handle and check for errors.
let topic = "pushNotifications";
admin.messaging().sendToTopic(topic, payload, options)
.then(function(response) {
console.log("Successfully sent message:", response);
console.log("Topic: " + topic);
res.status(200).send("success");
})
.catch(function(error) {
console.log("Error sending message:", error);
res.status(500).send("failure");
});
Send this jsone on your post parameter in registration_ids field you have to post array of your All device token that you want to send push notification
This is post request method body
{ "registration_ids" : [Send Array of Device Token],
"data" :
{
"image_url" : "send your image here"
"message" : "Send your message here" },
"notification" :
{
"title" : "APP Name",
"sound" : "default",
"priority" : "high"
}
}
Here is post URL
https://fcm.googleapis.com/fcm/send
and send key="Your Authorization key" in request HttpHeader field
Take reference for basic setup form here for cloud messaging
https://firebase.google.com/docs/cloud-messaging/ios/client

Resources