Cannot receive cloud function notification using Send to Topic Option - flutter

I am using Flutter and Dart to trigger cloud function push notification however, I cannot seem to receive any notification on my device. Can someone tell me what's wrong with my code?
const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp();
exports.myFunction = functions.database.instance("fm-90011")
.ref("orders/{userId}/{id}")
.onCreate((snapshot, context) => {
console.log(snapshot.val());
console.log("Inside push notification");
return admin.messaging().sendToTopic("orders",{notification:{title:"New Order",body:'Tap to view',clickAction:'FLUTTER_NOTIFICATION_CLICK'}});
});
Heres how the orders structure looks like in firebase realtime database.
In the cloud function log, I get the log messages as seen:

Based on the publish/subscribe model, FCM topic messaging allows you to send a message to multiple devices that have opted in to a particular topic. You compose topic messages as needed, and FCM handles routing and delivering the message reliably to the right devices.
For you to send a notification to topics,the device must be subscribed to the topic.
here is how to subscribe a device to a topic
....
FirebaseMessaging _firebaseMessaging = FirebaseMessaging.instance;
//subscribe to a notification
_firebaseMessaging.subscribeToTopic("orders");
make sure user is subscribed to orders before adding order.

Related

Unable to send firebase FCM message to multiple device in flutter using topics

I'm trying to register my app on a topics called weather , then trying to send push notification from postman. I have tried below code in flutter end to register or subscribe user to a topics called weather.
void main() async{
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
await FirebaseMessaging.instance.subscribeToTopic('weather');
runApp(MyApp());
}
Then, after tried to send message using postman I'm getting message id but not getting any FCM message in my device.
subscribeToTopic is't not the way that I have tried to subscribe the device to topics ?

flutter_local_notifications onNotificationReceived method - Flutter

Too long to read: The problem
Basically, I am looking for an onMessageReceived() callback but that works with flutter_local_notifications so I can handle and show the data to the user. This plugin only supports handling the onNotificationTap() action.
How am I expected to handle the message when the user receives it, for example, if they have Do Not Disturb on? Even if the local notification doesn't show, I need to show an Overlay at least, triggered by some onMessageReceived() function.
How can I update the notificationCount in my database when a local notification is received (scheduled)?
Description
In my project I am using:
Firebase Cloud Messaging (FCM)
flutter_local_notifications package.
When an event is scheduled in my app, the process is the following:
POST request to FCM with data only message.
My app receives the message through the onMessageReceived() callback.
Almost instantly I get 'Got a message whilst in the foreground!' message. This was triggered by the instant FCM data message.
The data inside the message triggers flutter_local_notifications to schedule a notification.
This scheduled local notification, received at a later date, cannot be handled (no OnMessage() function).
I don't schedule a notification directly on FCM because you can't do that from a post request (weird), but that would solve all my problems.
Problem
When the notification gets to the user's device, there is no way of handling the message (foreground or background)
I cannot display an Overlay with the notification, in case of the user being in the foreground
I cannot automatically update the notificationCount in my Firebase Realtime Database
Basically, I am looking for an onMessageReceived() callback but that works with flutter_local_notifications so I can handle and show the data to the user. This plugin only supports handling the onNotificationTap()` action.
Example of my process
This is what FCM has that flutter_local_notifications doesn't. Triggered when a notification is received by my app:
FirebaseMessaging.onMessage.listen((RemoteMessage message) async {
print('Got a message whilst in the foreground!');
[...]
if (scheduledDate != null) {
//using flutter_local_notifications
sendScheduledLocalNotification(itemTitle, 'Due Today', formattedDate);
//this notification, received at a later date, cannot be processed with this same function because it doesn't use FCM
}
//only shown with instant notifications (not scheduled)
if (notification != null) {
showOverlayNotification((context) {
return LocalNotificationOverlay(
title: notification.title!,
subtitle: notification.body!,
imageUrl: notification.imageUrl!,
);
}, duration: Duration(seconds: 3));
}
}
});
Yes, as far as I know we don't have the same stream option to listen to the notifications in the system tray for flutter_local_notifications as we have for FCM.
You can check this answer, It might help you.
I guess in the end you'd better do it in the back-end, and again this scheduled message being send/received via FCM.
I don't know about the mechanism that you're using and the function that sends the notification to user, but you can ignore sending notification to user if it has information about scheduling. Based on your code, scheduledDate and formattedDate are aware of it. So in your cloud function that sends the notifications you can instead of sending a notification, doing some task or triggering something(similar to the attached answer) and this will schedule sending that notification based on its time. Then in front-end for example you can update your databases every time you get a notification from FCM, because you didn't send them in the first place and you actually scheduled sending them in the planed time.

Flutter : Handle push notification message that come from non-firebase source

My app is setup to use firebase for push notification. I see the push and the data when I send a message thru firebase
FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
print('Got a message whilst in the background!');
print('Message data: ${message.data}');
});
//trap when app is in foreground
FirebaseMessaging.onMessage.listen(
(RemoteMessage message) {
}
Now , another third party vendor(iterable) is sending push message. I see the popup but how do I get the data from the message. The firebase handler does not get triggered
Thanks
You can't get the message data from the FirebaseMessaging if you are not using Firebase.
Firebase messaging is exclusive to firebase, so you can't use it to get other third-party notifications. Your third-party notification provider will provide SDK, you need to integrate it into your app, in order to get the data from the message.

Sending push notifications when a user likes your post like Instagram

I'm practicing Swift programming by trying to build Instagram for fun. I am using firebase as my database. I was able to set up the activity page where it shows a user has liked/commented on your post.
Now I am wondering how can I actually send a push notification when that happens? I tried using FirebaseMessaging but all I can really do is send messages from firebase directly.
How do I send a specific user a push notification that someone has liked their post?
You can try using Firebase functions. Here are the basic concepts:
To receive notifications, user must subscribe to a "topic" using subscribeToTopic(String topic)
Whenever a post from that topic is created, you use firebase messaging to send message to that topic
To do that, you need to host a function to firebase. That function listens to new posts being posted at whatever node you are using
Everytime a new post is written to that node, it sends the message
Here is the link to the of an example Firebase Functions Example (the function to be hosted is sendNotificationToLocation).
Check this on how to handle subscribing/unsubscribing and handling message/notification Firebase messaging
First do the all configurations for Firebase Cloud Messaging.
Then get firebase registration token of the user whom you want to send a push notifications to.
follow this link for detailed explanation

How can I tell if a push notification was successfully delivered in Azure NotificationHubs?

I have an app with a simple messenger component to it. When user1 sends a message to user2 I am using Azure Notification Hubs to send a push notification to user2. Since I am using Notification Hubs to register the user's devices for push notifications, I don't know which phone OS's they have registered with, so just queue a notification for each type I support:
NotificationOutcome outcome1 = await hub.SendAppleNativeNotificationAsync(jsoniOSPayload, tags);
NotificationOutcome outcome2 = await hub.SendGcmNativeNotificationAsync(jsonAndroidPayload, tags);
...(etc.)
However, we need to handle the case where an app has been deleted. When this happens, we need to send the user an email if a push notification could not be sent to any of their devices.
My question is: how can I tell if at least one notification was successfully delivered to a users device? I know about the NotificationHubClient.EnableTestSend property, which does cause the NotificationOutcome object to have a success count. This would work perfectly, but the documentation indicates this would not be optimal in production:
"When test send is enabled, the following occurs: All notifications
only reach up to 10 devices for each send call.The Send* methods
return a list of the outcomes for all those notification deliveries.
The possible outcomes are the same as displayed in telemetry. Outcomes
includes things like authentication errors, throttling errors,
successful deliveries, and so on.This mode is for test purposes only,
not for production, and is throttled."
Any suggestions would be appreciated!
how can I tell if at least one notification was successfully delivered to a users device?
As you mentioned that NotificationHubClient.EnableTestSend is used for debugging and limited to 10 devices.
If we want to get the count of successfully delivered, we can use function NotificationHubClient.GetNotificationOutcomeDetailsAsync(string notificationId), more details please refer to document.
Demo code:
NotificationHubClient hub = NotificationHubClient.CreateClientFromConnectionString("Endpoint=sb://notificationnamespace.servicebus.windows.net/;SharedAccessKeyName=DefaultFullSharedAccessSignature;SharedAccessKey=xxxxxxx", "NotificationHub Name");
string message = "{\"title\":\"((Notification title))\",\"description\":\"Hello from Azure\"}";
var result = await hub.SendGcmNativeNotificationAsync(message); //GCM for example.
var notificationDetails = await hub.GetNotificationOutcomeDetailsAsync(result.NotificationId);
return notificationDetails;
Note: It is just for standard pricing tier.