I am trying to send an FCM topic message to my React Native mobile app, but they don't seem to be going through. I am using NodeJs as follows and logging the output to show that the message is getting sent successfully (no issues with android):
admin
.messaging()
.send({
data: {
title,
body,
lat: data.Location.Latitude.toString(),
lng: data.Location.Longitude.toString(),
},
android: {
priority: "high",
data: {
sound: "alert",
},
},
apns: {
payload: {
aps: {
contentAvailable: true,
},
},
headers: {
'apns-push-type': 'background',
'apns-priority': '5',
'apns-topic': 'com.xxxx',
},
},
topic: topic,
})
The react app is subscribed to the topic as follows:
useEffect(() => {
await requestUserPermissions();
messaging().subscribeToTopic(Config.INCIDENTS_TOPIC);
messaging().onMessage(sendMessage);
messaging().setBackgroundMessageHandler(sendMessage);
});
const sendMessage = (remoteMessage) => {
if (Platform.OS === 'ios') {
notificationRadiusCalculationService.sendMessage(remoteMessage);
}
};
I have set a breakpoint in the sendMessage and its never being hit.My APN was registered in firebase.
Related
https://blog.logrocket.com/flutter-push-notifications-with-firebase-cloud-messaging/
// For handling the received notifications
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
// Parse the message received
PushNotification notification = PushNotification(
title: message.notification?.title,
body: message.notification?.body,
);
As we can see, notification is one field in RemoteMessage structure.
and here: https://pub.dev/packages/firebase_messaging/example
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
// If you're going to use other Firebase services in the background, such as Firestore,
// make sure you call `initializeApp` before using other Firebase services.
await Firebase.initializeApp();
print('Handling a background message ${message.messageId}');
}
messageId is another field in RemoteMessage.
What other fields are in this RemoteMessage structure? I tried to find its API but failed.
Can we override it and fill our own fields?
Here is the structure of RemoteMessage. You can add your custom data to the data property of it.
const RemoteMessage(
{this.senderId,
this.category,
this.collapseKey,
this.contentAvailable = false,
this.data = const <String, dynamic>{},
this.from,
this.messageId,
this.messageType,
this.mutableContent = false,
this.notification,
this.sentTime,
this.threadId,
this.ttl});
A usual notification payload when send from the backend/cloud functions looks like this:
const payload = {
notification: {
title: title,
body: message,
},
data: {
uid,
},
webpush: {
notification: {
icon: photoURL,
},
},
android: {
notification: {
image: photoURL,
},
},
apns: {
payload: {
aps: {
"mutable-content": 1,
},
},
fcm_options: {
image: photoURL,
},
},
};
I want to send FCM to various tokens saved in the firestore document as an array with the use of firebase cloud functions. Also is it possible to send the FCM to platform-specific options in the payload. I tried a lot of examples and none worked for me. I attached the code for reference.
Tokens in firestore document:
...
let tokens2 = [];
await admin.firestore().doc(`Users/${uid}`).get().then(queryResult => {
let tokensResult = queryResult.data().tokens;
tokens2 = tokensResult;
});
let message = {
notification: {
title: title,
body: content
},
data: {
channel_id: "some_channel"
},
android: {
notification: {
notificationCount: 1
}
},
apns: {
payload: {
aps: {
badge: 42,
sound: "default"
}
}
},
token: [tokens2]
};
let response = await admin.messaging().send(message).catch(e => console.log(e));;
console.log(response);
the last error on my function console:
I also tried with sendToDevice and send multicast but no lucky
any help is welcome :)
I am trying to send notification in react native via rest api. In response i'm getting success :1. The problem here is i'm not getting notification in emulator.
const token = await firebase.messaging().getToken();
console.log("token in sendNotification ",token)
const FIREBASE_API_KEY = "firebaseApiKey";
const message = {
to :token,
notification: {
title: "This is a Notification",
boby: "This is the body of the Notification",
vibrate: 1,
sound: 1,
show_in_foreground: true,
priority: "high",
content_available: true,
}
}
let headers = new Headers({
"Content-Type" : "application/json",
Authorization: "key=" + FIREBASE_API_KEY,
})
try {
let response = await fetch ("https://fcm.googleapis.com/fcm/send",{
method: "POST",
headers,
body: JSON.stringify(message),
})
response = await response.json();
console.log("response ", response);
} catch (error) {
console.log("error ", error);
}
https://firebase.google.com/docs/cloud-messaging/js/receive
You can follow the incoming message documentation
// Handle incoming messages. Called when:
// - a message is received while the app has a focus
// - the user clicks on an app notification created by a service worker
// `messaging.setBackgroundMessageHandler` handler.
messaging.onMessage((payload) => {
console.log('Message received. ', payload);
// ...
});
In useEffect of App.js
import React,{useEffect} from 'react'
import{View,Text} from 'react-native';
async function onDisplayNotification() {
// Create a channel
const channelId = await notifee.createChannel({
id: 'default',
name: 'Default Channel',
});
// Display a notification
await notifee.displayNotification({
title: 'Notification Title',
body: 'Main body content of the notification',
android: {
channelId,
smallIcon: 'ic_launcher', // optional, defaults to 'ic_launcher'.
},
});
}
const App=()=> {
useEffect(() => {
// Assume a message-notification contains a "type" property in the data payload of the screen to open
messaging().onMessage((payload) => {
console.log('Message received. ', payload);
onDisplayNotification();
// ...
});
messaging().onNotificationOpenedApp(remoteMessage => {
console.log(
'Notification caused app to open from background state:',
remoteMessage.notification,
);
alert("Notification");
});
// Check whether an initial notification is available
messaging()
.getInitialNotification()
.then(remoteMessage => {
if (remoteMessage) {
console.log(
'Notification caused app to open from quit state:',
remoteMessage.notification,
);
}
});
}, []);
return (
<View>
</View>
)
}
export default App;
I'm trying to send Push Notifications with Firebase Cloud Functions with platform specific configuration. I got following config from https://firebase.google.com/docs/cloud-messaging/send-message
var message = {
notification: {
title: '$GOOG up 1.43% on the day',
body: '$GOOG gained 11.80 points to close at 835.67, up 1.43% on the day.',
},
data: {
channel_id: threadId,
},
android: {
ttl: 3600 * 1000,
notification: {
icon: 'stock_ticker_update',
color: '#f45342',
},
},
apns: {
payload: {
aps: {
badge: 42,
},
},
},
};
but got error for admin.messaging().sendToDevice(deviceToken, message)
Messaging payload contains an invalid "android" property. Valid properties are "data" and "notification"
Any idea what is wrong here? Or maybe some samples of proper configuration for iOS/Android platforms?
sendToDevice() is a function that uses the legacy FCM HTTP endpoint. The legacy endpoint doesn't offer platform-specific fields. In order to get that functionality, you can use the new endpoint through the send() function. You may need to update your version of the Admin SDK. You can see an example in the documentation here.
For the code you provided, for example, you would send a message like this:
let message = {
notification: {
title: '$GOOG up 1.43% on the day',
body: '$GOOG gained 11.80 points to close at 835.67, up 1.43% on the day.',
},
data: {
channel_id: threadId,
},
android: {
ttl: 3600 * 1000,
notification: {
icon: 'stock_ticker_update',
color: '#f45342',
},
},
apns: {
payload: {
aps: {
badge: 42,
},
},
},
token: deviceToken,
};
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:', error);
});
Notice the device token is now in the message object.
I have an Ionic mobile application that receives notifications from the Firebase console. The application correctly receives notifications in background and foreground. However, when I send notifications from Node.js with firebase-admin plugin, only foreground notification arrives. Notifications do not arrive when the application is in the background.
What could be the problem? Does anyone know why the mobile app receive notifications in background with Firebase console but not with Node.js?
Thanks for any idea.
This is the code in the mobile application (app.component.ts):
this.fcm.subscribeToTopic('all');
platform.ready().then(() => {
this.fcm.getToken().then(token => {
console.log(token);
let alert = this.alertCtrl.create({
title: '¡new notification!',
message: token,
buttons: [
{
text: 'Cancel',
role: 'cancel',
handler: () => {
console.log('cancel button');
}
},
{
text: 'OK',
handler: () => {
console.log('ok button');
this.navCtrl.push('DetailPage');
}
}
]
});
alert.present();
});
this.fcm.onNotification().subscribe(data => {
alert('message received')
if(data.wasTapped) {
console.info("Received in background");
} else {
console.info("Received in foreground");
};
});
statusBar.styleDefault();
splashScreen.hide();
});
This is the code in Node.js:
var sys = require("util");
var admin = require('firebase-admin');
var serviceAccount = require('./xxxx.json');
var registrationToken ="xxxxxx";
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "https://xxxxx"
});
var message = {
data: {
score: '850',
time: '2:45'
},
token: registrationToken
};
admin.messaging().send(message)
.then(function(response) {
console.log("Successfully sent message:", response);
})
.catch(function(error){
console.log("Error sending message", error);
});