Is there alternative to ttl "time to live" for iOS in firebase cloud messaging? - ios

I am sending the notifications using admin sdk.
This is my payload. I was able to set ttl (Time to Live) for Android but I am not sure how I can make it for iOS.
Basically if notification fails to send, then I dont want to resend it at all.
const payload = {
notification: {
title: 'New Appointments!',
body: '',
},
data: {},
android: {
ttl: 1000,
},
apns: {
payload: {
aps: {
badge: 1,
"sound":"default"
},
},
},
};
admin.messaging().send(payload).then((response) => {})

I think you're looking for apns-expiration:
A UNIX epoch date expressed in seconds (UTC). This header identifies the date when the notification is no longer valid and can be discarded.
If this value is nonzero, APNs stores the notification and tries to deliver it at least once, repeating the attempt as needed if it is unable to deliver the notification the first time. If the value is 0, APNs treats the notification as if it expires immediately and does not store the notification or attempt to redeliver it.
An example of this is seen in the FCM docs for ttl:
{
"message":{
"token":"bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
"data":{
"Nick" : "Mario",
"body" : "great match!",
"Room" : "PortugalVSDenmark"
},
"apns":{
"headers":{
"apns-expiration":"1604750400"
}
},
"android":{
"ttl":"4500s"
},
"webpush":{
"headers":{
"TTL":"4500"
}
}
}
}

The Problem I had was wrong format because I was reading the wrong documentation.
https://firebase.google.com/docs/reference/fcm/rest/v1/projects.messages#ApnsConfig.
"apns":{
headers:{
"apns-expiration":"1604750400"
}
}

Related

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.

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-admin doesn't send iOS APN notification

I can send push notifications from Firebase Console Notifications to my iOS device, and it works perfectly being the app in foreground and background.
When I try to send them using Firebase-admin by NodeJS it only works when the app is in foreground, in background nothing happens.
I think that the communications between FCM-APNs are good because it works with the console.
This is my NodeJS code:
function sendFCM(registration_ids, data, collapseKey) {
const options = {
priority: "high",
collapseKey : collapseKey,
contentAvailable : true,
timeToLive: 60 * 60 * 24
};
const payload = {
data: data,
notification: {
title: "My title",
text: "My description",
sound : "default"
}
}
admin.messaging().sendToDevice(registration_ids, payload, options)
.then(function(response) {
console.log("Successfully sent message:", response);
})
.catch(function(error) {
console.log("Error sending message:", error);
});
}
What do you think that it's happening? Do you know some way to log the issue?
The Server Protocol documentation indicates the key for notification text is body, not text. See if this change makes a difference:
const payload = {
data: data,
notification: {
title: "My title",
body: "My description", // <= CHANGE
sound : "default"
}
}

Firebase Cloud Messaging not sending aps payload in correct format for iOS Notification Content & Service Extensions

I'm trying to implement notifications using Firebase. The notification is received correctly when the app is in the background or foreground. So, the basic mechanics are working.
Now I've added Content Extensions and Service Extensions to the app. The Content Extension works when I use a local notification, but the Firebase message payload seems incorrect as far as the optional fields are considered. Here is a link to an image of my console:
And here is the Firebase remote notification payload that comes across (with some of the long Google numbers edited for anonymity:
{
aps =
{
alert =
{
body = "Eureka! 11";
title = "Patient is not doing well";
};
};
category = provider-body-panel;
gcm.message_id = 0:149073;
gcm.n.e = 1;
google.c.a.c_id = 2825604;
google.c.a.e = 1;
google.c.a.ts = 149073;
google.c.a.udt = 0;
mutable-content = 1;
}
It appears that the "category" and "mutable-content" are not in the correct place. They should be in the aps payload.
How can I get those options to be in the payload so that my app can correctly parse it and connect it with the Content and Service Extensions?
To start off, I'm going to mention that there are two types of message payloads for FCM. notification and data. See the documentation here
When sending notifications through the Firebase Notifications Console, it will be treated as a notification payload. However, if you add in Custom Data, it will add it in the payload as a custom key-value pair.
For example, in your post, the FCM payload should look something like this:
{
"notification": {
"body" : "Eureka!",
"title": "Patient is not doing well"
},
"data": {
"category": "provider-body-panel",
"mutable-content" : true,
"click_action" : "provider-body-panel"
}
}
What's wrong?
click_action should be inside notification.
mutable-content should be mutable_content (notice the underscore) and should be on the same level as notification.
(this one I might've misunderstood, but) There is no category parameter for FCM, click_action already corresponds to it.
See the docs for the parameters here.
It it is currently not possible to set the value for click_action and mutable_content when using the Firebase Notifications Console. You'll have to build the payload yourself, something like this:
{
"to": "<REGISTRATION_TOKEN_HERE>",
"mutable_content" : true,
"notification": {
"body" : "Eureka!",
"title": "Patient is not doing well",
"click_action" : "provider-body-panel"
}
}
Then send it from your own App Server. You could also do this by using Postman or cURL
"mutable-content should be "mutable_content" (keyword for firebase server to send as mutable-content for IOS) as you mentioned in your post, I think you left out in edit.
Below is an example with also the corrected format for the data section in the json sent to the FCM server.
So update would be:
{
"to" : "YOUR firebase messaging registration id here",
"mutable_content":true,
"notification": {
"title": "Its about time",
"body": "To go online Amigo",
"click_action": "NotificationCategoryIdentifier ForYourNotificationActions"
},
"data":{
"customKey":"custom data you want to appear in the message payload"
"media-attachment":"mycustom image url",
"catalogID":"mycustom catalog for my custom app"
}
}
Update Firebase Admin SDK and use sendMulticast(payload) method
var admin = require("firebase-admin")
admin.initializeApp({
credential: admin.credential.applicationDefault(),
});
// Create a list containing up to 500 registration tokens.
// These registration tokens come from the client FCM SDKs.
const registrationTokens = [
'YOUR_REGISTRATION_TOKEN_1',
// …
'YOUR_REGISTRATION_TOKEN_N',
];
// See documentation on defining a message payload.
var message = {
notification: {
title: '$FooCorp up 1.43% on the day',
body: '$FooCorp gained 11.80 points to close at 835.67, up 1.43% on the day.'
},
tokens: registrationTokens,
apns: {
payload: {
aps: {
'mutable-content': true, // use single quote
'category': 'INVITE_CATEGORY' // use single quote
}
},
},
};
// Send a message to the device corresponding to the provided
// registration tokens.
admin.messaging().sendMulticast(message)
.then((response) => {
if (response.failureCount > 0) {
const failedTokens = [];
response.responses.forEach((resp, idx) => {
if (!resp.success) {
failedTokens.push(registrationTokens[idx]);
}
});
console.log('List of tokens that caused failures: ' + failedTokens);
}
});
Ref: https://firebase.google.com/docs/cloud-messaging/send-message#send_messages_to_specific_devices
This worked for me with Cloud functions with Node.js
const payload = {
notification: {
title: name,
body: messageText,
badge: "1",
mutable_content: "true"
},
data: {
type: "MESSAGE",
fromUserId: name,
attachmentUrl: imageUrl
}};

Setting priority Firebase Messaging in Cloud Function for Firebase

I'm using Firebase Messaging to send notifications to users of my iPhone app. In order to not expose the app's messaging server key on the client side I'm using Cloud Function for Firebase to send the notifications to specific topics. Before this I did it from the client side on the app and was able to set the message's priority by making a JSON of this format:
// Swift code in iPhone app
let body: [String: Any] = ["to": "/topics/\(currentPet)",
"priority" : "high",
"notification" : [
"body" : "\(events[eventType]) for \(petsName.localizedCapitalized)",
"title" : "\(myName.localizedCapitalized) just logged an event",
"data" : ["personSent": myId]
]
]
Now in my cloud function I'm trying to make a payload of the same general format, but keep running into the error:
Messaging payload contains an invalid "priority" property. Valid properties are "data" and "notification".
Here's my payload formatting and sending:
const payload = {
'notification': {
'title': `${toTitleCase(name)} just logged an event`,
'body': `${events[eventType]} for ${toTitleCase(petName)}`,
'sound': 'default',
'data': userSent
},
'priority': 'high'
};
admin.messaging().sendToTopic(pet_Id, payload);
Does anybody know how I would accomplish setting the priority? Should I just manually do an HTTP POST instead of using admin.messaging().sendToTopic()?
From the Firebase Cloud Messaging documentation on sending messages with the Admin SDK:
// Set the message as high priority and have it expire after 24 hours.
var options = {
priority: "high",
timeToLive: 60 * 60 * 24
};
// Send a message to the device corresponding to the provided
// registration token with the provided options.
admin.messaging().sendToDevice(registrationToken, payload, options)
.then(function(response) {
console.log("Successfully sent message:", response);
})
.catch(function(error) {
console.log("Error sending message:", error);
});
The difference is that the priority (and ttl in the example) is passed as a separate options argument instead of in the payload.

Resources