In case you've been wondering (I was) how to seach for stuff in Firebase's Cloud Firestore I found it randomly today and would like to share it:
Combining data+notification payload in FCM Android
If you send this payload to an iOS device via FCM, and also invoke UNUserNotificationCenter
's didReceive response: withCompletionHandler
callback method, iOS will both display a text notification as well as allow you app some background time to deal with the data object you're sending along your push notification.
Unfortunately on Android even using my recommended payload you won't achieve this behavior. If you send both notification
and data
, only the notification will be shown, and the OnMessageReceived
callback method won't be called to handle the data object.
But if you're in charge of the FCM payload creation, you can put the notification's title and body into the data
object like this:
{
"message":{
"token":"<device registration id>",
"data":{
"account":{
"first-name":"Igor",
"last-name":"Z"
},
"androidTitle":"title",
"androidBody":"body"
}
}
}
And when OnMessageReceived
is called with the contents of this payload, you just create a local heads-up notification based on the info in androidTitle
and androidBody
with this code:
This code is a bit verbose, but is guaranteed to be working on all current versions of Android, which is invaluable 🙂 You just put androidTitle
and androidBody
as parameters of the method above and a nice default nofitication will appear on each message.
Now you can enjoy notification+data push notifications in a single message on Android with this hack, instead of sending two messages each time.
Firebase Android notification payload
Unlike iOS, for Android Firebase's FCM server accepts payload in slightly different form:
{
"message":{
"token":"<device registration id>",
"android":{
"notification":{
"title":"title",
"sound":"default",
"body":"body"
},
"priority":"high"
},
"data":{
"account":{
"first-name":"Igor",
"last-name":"Z"
}
}
}
}
But there's a caveat: when both the android
and data
objects are present - only the notification is shown, without data being passed to OnMessageReceived
FCM callback method. So in order to send both data and notification at the same time on Android you either have to send two messages - one data and one notification. Or to be a bit more creative 🙂
Firebase iOS push payload
If you're using Firebase and its FCM (Firebase Cloud Messaging) server directly to send out notifications to iOS users, you might wonder what kind of payload you should send to Firebase in order for the information to be delivered.
So wonder no more 🙂
{
"message":{
"token":"<device registration id>",
"apns":{
"payload":{
"aps":{
"content-available":1,
"alert":{
"title":"title",
"subtitle":"subtitle",
"body":"body"
},
"badge":7,
"sound":"default"
}
}
},
"data":{
"account":{
"first-name":"Igor",
"last-name":"Z"
}
}
}
}
In case you need, here's an example of the payload for Android