Using Flutter for the first time and have implemented Firebase Cloud Messaging. I can sent a notification from Notification Composer in the Firebase Console. I can see in the debug-console on Android whilst the app is in foreground that it receives the data I have set in Custom Data.
_firebaseMessaging.configure(
onMessage: (Map<String, dynamic> message) {
print('on message $message');
},
However I am wondering how to get not only the Custom Data but also the Message Text and Message Title.
if you are trying to get the string for title and body that comes in the message object, you can do something like this:
final title = message['notification']['title'] ?? '';
final body = message['notification']['body'] ?? '';
Related
I am trying to send push notifications to another iOS device using firebase cloud functions but I receive the following error below when attempting to do so:
'FirebaseMessagingError: Invalid registration token provided. Make sure it matches the registration token the client app receives from registering with FCM.'
This is the registration token I am trying to send to 6e04bb35f06e2d981d5603bbd229eeab5ee5649f6af7b4ecc3894be6ad1574d7 which is the same token I have saved in my realtime database:
Below is my onCreate function:
exports.onMessageCreate = functions.database.ref('/messages/{chatId}/{messageId}').onCreate((snapshot, context) => {
const chatId = context.params.chatId;
const receiverId = chatId.replace(context.auth.uid, '');
const root = snapshot.ref.root;
return admin.database().ref(`/users/${receiverId}/regToken`).once('value').then(tokenSnap => {
var regTokenRef = tokenSnap.val();
const payload = {
notification: {
title: 'title',
body: snapshot.val().text,
}
};
const options = { priority: "high" };
return admin.messaging().sendToDevice(regTokenRef, payload, options).then(function(response){
console.log("Successfully sent message: ", response);
console.log(response.results[0].error);
}).catch(function(error) {
console.log("Error sending message: ", error);
});
});
});
Do you know what may be causing this error? I am not too sure what I need to check here. Is the format wrong here? Does it need to be in quotes? I have looked at other links but they haven't really helped.
I am importing '#react-native-community/push-notification-ios' to generate the token. I think this may be the problem. I was having issues to use the messaging from firebase. Is this the issue?
Please see below the didFinishLaunchingWithOptions method updated in my AppDelegate.m file. Have I placed the below code correctly? When this is added it is causing my app to appear blank when launching the simulator with the FirebaseError: Firebase: No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp() (app/no-app).? However, when removed my app launches but with still has the FirebaseError.
if ([FIRApp defaultApp] == nil) {
[FIRApp configure];
}
#react-native-community/push-notification-ios is not able to generate an FCM token, only APN token: https://github.com/react-native-push-notification-ios/push-notification-ios/issues/117
If you want to use firebase, you need to generate the token from the messaging package of firebase to have a FCM one.
I have a flutter app that in some point the administrator users can save one publication.
Now I want all users receive a notification when that publication is posted (with it title, description ..etc).
How could I do that with firebase messaging?
I already wrote this code which, if I go to firebase console and generate a example notification, I receive it normally:
class PushNotificationsManager {
PushNotificationsManager._();
factory PushNotificationsManager() => _instance;
static final PushNotificationsManager _instance = PushNotificationsManager._();
final FirebaseMessaging _firebaseMessaging = FirebaseMessaging();
Future<void> init() async {
if(Platform.isIOS){
_firebaseMessaging.requestNotificationPermissions(IosNotificationSettings());
}
_firebaseMessaging.configure(
// Called when the app is in the foreground and we receive a push notif.
onMessage: (Map<String, dynamic> message) async {
print("onMessage: ${message}");
print(message['notification']['body']);
},
// Called when the app has been closed completely and its opened
// from the notification directly
onLaunch: (Map<String, dynamic> message) async {
print("onMessage: ${message}");
},
// Called when the app is in the background and its opened from the notif
onResume: (Map<String, dynamic> message) async {
print("onMessage: ${message}");
},
);
}
In summary, how could I generate a notification (with the title and description created) to all users when the admin creates a new publication without going to firebase console to generate it manually?
I'm using firebase_messaging: ^7.0.3
Update
I tried to do this:
Future sendNotification() async {
final String url = 'https://fcm.googleapis.com/fcm/send';
var token = await _firebaseMessaging.getToken();
var data;
data='{"notification": {"body": "this is a body", "title": "this is a title"}, "priority": "high", "data": {"click_action": "FLUTTER_NOTIFICATION_CLICK"}, "to": "${token}"}';
final response = await http.post(
url,
headers: <String, String>{"Content-Type": "application/json", "Keep-Alive" : "timeout=5", "Authorization" : "key=${mykey}"},
body: data
);
print(response.body);
}
...calling this in the method I save the event in firebase only displays the notification to my phone, and not to every phone, there's a way to do it in this form?
You can do this using a cloud function. Either by calling the function from your app when the publication is created, or by having the cloud function listen for a new document. See this Medium post for some ideas: https://medium.com/#jerinamathews/send-firebase-cloud-messaging-fcm-to-a-topic-using-cloud-function-when-realtime-database-value-fa78fa758549
Update
Based on your update, I suggest you look at using a 'Topic' rather than a specific token (that applies to only one device). To use a Topic you need to ensure all users automatically subscribe to the chosen topic when they open the app (they can subscribe to the same topic each time, it has no negative impact). FCM maintains a list of subscribed device tokens against the topic.
I haven't used topic via an http post so I cannot confirm it is possible but I am assuming if you can send to a token you must be able to send to a topic.
I have 2 different cloud functions that send a notification to the device. one is sendNewChatMessageNotification and the other one is sendNewFriendRequestNotification.
How can I get the function name that triggered the onMessage method of the firebaseMessaging instance? because I want to show different messages for the different cloud functions.
final firebaseMessaging = FirebaseMessaging();
firebaseMessaging.getToken().then((tokenVal) {
fcmToken = tokenVal;
firebaseMessaging.configure(
onMessage: (Map<String, dynamic> message) async {
// -----> how can I get the cloudFunctionName ??
if(cloudFunctionName == "sendNewFriendRequestNotification"){
//show friend request notification
}else if(cloudFunctionName == "sendNewChatMessageNotification"){
//show new chat message notification
}
}
You will have to code your function to send that string value in the payload of the message. It will not be sent automatically.
Im use Flutter and Firebase Messaging.
I im configure Firebase like in example: firebaseMessaging.configure(
onMessage: ...
onLaunch: ...
onResume: ...
)
But i wanna see push-notification even when app is open.
Roughly speaking onMessage should work like onResume. How can i do this?
onMessage: (Map<String, dynamic> message) async {
showNotification(message);
print('on message $message');
}
showNotification(Map<String, dynamic> msg) async {
var android = new AndroidNotificationDetails(
'your channel id',//channel id
"your channel name",//channel name
"your channel description",//channel desc todo set all this right
icon: 'mipmap/launcher_icon'//add your icon here
);
var iOS = new IOSNotificationDetails();
var platform = new NotificationDetails(android, iOS);
await flutterLocalNotificationsPlugin
.show(0, msg['notification']['title'], msg['notification']['body'], platform);
}
I used flutter_local_notifications: ^1.2.2 to show local notification foreground.
Additionally, if you are implementing for IOS don't forget to ask for notification permission.
I am using Firebase in a Flutter app. To send notifications, I am using Firebase Messaging plugin. Whenever I send a notification using Firebase website, the notification just opens the app when user clicks on it. I want to send a notification which opens a URL instead of the app.
I don't know if this information is useful: while composing a notification on Firestore, I always put click_action as FLUTTER_NOTIFICATION_CLICK in "Custom data" section in Additional Options.
You can use onLaunch() and onResume() methods to handle notification's opening action.
for more information of notification's reaction on different platforms please see below link:
https://pub.dev/packages/firebase_messaging#receiving-messages
_firebaseMessaging.configure(
onMessage: (Map<String, dynamic> message) async {
print("onMessage: $message");
},
onBackgroundMessage: myBackgroundMessageHandler,
onLaunch: (Map<String, dynamic> message) async {
print("onLaunch: $message");
},
onResume: (Map<String, dynamic> message) async {
print("onResume: $message");
},
);
And you can use url_launcher to open URLs:
https://pub.dev/packages/url_launcher