Expo push notifications listener not firing - react-native

I'm implementing push notifications in an app, but I need to handle the notification to navigate to a specific screen. The problem is that my listener never fires, I searched a lot on google and tried a lot of things but none of them worked..
I'm using AWS SNS together with FCM to send the push.
What I have is this in my App.tsx:
componentDidMount() {
Notifications.addListener(notification => {
alert("IT WORKED")
})
}
But ofcourse this alert is never called..
I read this issue https://github.com/expo/expo/issues/4183 and it seems that the format of the push matters, so right now I'm sending the push in this format:
{
"GCM": "{ \"notification\": { \"message\": \"Sample message for Android endpoints\", \"title\": \"Hello You...\" } }"
}
And I receive the push, but when I click on it to open the app, doesn't fire my listener, but in the issue the guy said to send like this:
{
"GCM": "{ \"data\": { \"message\": \"Sample message for Android endpoints\", \"title\": \"Hello world...\", \"body\": \"msg body\", \"experienceId\": \"#expousername/app-slug\" } }"
}
But if I send like this, I don't even receive the push.
What I'm doing wrong?

Related

Message format for deeplink with react-native-push-notification

I am using react-native-push-notification library to send local notifications from my ios app. I have setup deeplink using react navigation. I have also managed the local push notification to deeplink into specific app screen on click. But this requires me to set the in the message property. This means the resulting lo shows the URL in its display. This is ugly and I would like to hide the URL. Any pointers?
Here is how i schedule local notification
PushNotification.localNotificationSchedule({
title: "main title",
subtitle: "fake sub title",
message: "example://detail/one",
bigText: "My big text that will be shown when expanded",
date: new Date(Date.now() + 10 * 1000),
allowWhileIdle: false,
});
Here is my onNotification code
onNotification: function (notification) {
console.log("NOTIFICATION:", notification);
let isClicked = notification.data.userInteraction === 1
if (isClicked) {
Linking.openURL(notification.message)
}
notification.finish(PushNotificationIOS.FetchResult.NoData);
},
Now this results in the example://detail/one url being displayed in notification. How do i achieve this?
Not exactly a solution to the above issue. But I switched to Notifee for local push notifications. And it just worked! So much easier to install and very minimal configuration needed. Was just an intuitive I expected the notification library to be.

React native push notification not shown when app is closed

I have a react native app. I am using react-native-push-notification npm module for push notifications (mainly local notifications). This is working fine.
I use OneSignal service for remote notifications which works fine as well.
However, now I am trying to use react-native-freshchat-sdk (third party tool) to provide chat functionality within the app.
I have the following code
PushNotification.configure({
// (optional) Called when Token is generated (iOS and Android)
onRegister: function (token: any) {
console.log('TOKEN:', token)
dispatch(tokenGenerated(token));
},
//(required) Called when a remote or local notification is opened or received
onNotification: function (notification: any) {
console.log(`**********notification received ********************* : ${JSON.stringify(notification)}`)
Freshchat.isFreshchatNotification(notification.data, (freshchatNotification: any) => {
if (freshchatNotification) {
console.log(`**********freshchatNotification received *********************`)
Freshchat.handlePushNotification(notification.data);
} else {
console.log(`**********some other notification*********************`)
}
})
},
Things work fine when the app is in the foreground or background. I do get remote notifications from FreshChat with the chat content. FreshChat uses FCM for sending notifications.
However, when the app is closed or killed, I do not get the notifications (atleast they are not shown in the tray)
When I open the chat, I can see the chat message there.
Chat remote notification looks like the following
{
"foreground": false,
"userInteraction": false,
"id": "-1665678567",
"data": {
"channel_id": "748134",
"app_id": "5787643203",
"notif_type": "1",
"msg_alias": "8343f922-9dfa-4fe9-9220b-61af8902e7650",
"source": "freshchat_user",
"body": "heelo world message",
"timestamp": "1660956855495",
"user_name": "Foo Bar",
"target_user_alias": "ssd1232-75df-87f0-fsdsd",
"conv_id": "6479825358242"
}
}
I have been scratching my head to understand why I am not getting remote notifications when the app is closed. What's confusing me even more is that I get OneSignal remote notifications even when the app is closed. I would like to see similar behaviour with the remote notification sent by FreshChat
Any help pointers would be really handy. I have been stuck with these for days now and have no clue what's going wrong.
Thanks in advance

Duplicate fcm push notification in react native android backgroundhandler

I developed react native application with rnfirebase and notifee for sending the push notification. foreground is working properly, message is displayed only once. but the background notification is displaying twice like one is from messaging().setBackgroundMessageHandler and another one is android's default push notification. First message is from default push notification and next one is from firebase messaging. So how do I remove android's default push notification. I'm also checked that first default notification is not using the firebase messaging and notifee. It's comes from outside of react native like android's native push notification
The notifications that you are seeing are most likely one from firebase and another from Notifee.
In my project I was handling the notifications that were coming from firebase via firebase.messaging().onMessage and inside this listener I was showing a local notification using Notifee so that the notification shows in the foreground.
async showNotificationInForeground(message: FirebaseMessagingTypes.RemoteMessage) {
const { messageId, notification, data } = message
const channelId = await Notifee.createChannel({
id: messageId,
name: 'Pressable Channel',
importance: AndroidImportance.HIGH,
})
await Notifee.displayNotification({
title: notification?.title || '',
body: notification?.body || '',
data,
android: {
channelId,
importance: AndroidImportance.HIGH,
pressAction: {
id: messageId,
},
smallIcon: 'ic_stat_name',
localOnly: true,
},
})
}
However what was happening was that I was calling this showNotificationInForeground method to show the local Notifee notification on both firebase's background and messaging listeners ie: firebase.messaging().onMessage and firebase.messaging().setBackgroundMessageHandler
So what I ended up doing was only calling the showNotificationInForeground method in onMessage listener and not in setBackgroundMessageHandler, which resulted in showing the local notification in the foreground, and the firebase notification in the background.
If this is not the case for you, you are most likely registering an extra notification receiver inside your AndroidManifest.xml file which is causing the duplication
I had the same problem, where there were two notifications a) 1 from notifee (which I wanted to keep) b) from FCM (which I didnt want).
Sending a data only message from my custom server solved the issue. Below is a snippet of the serverside for sending data only message :
const admin = require("firebase-admin");
// Do other stuff like create an express server to listen and trigger sending message
// Note dont forget to to initialize the app
await admin.messaging().sendToDevice(
tokens, // ['token_1', 'token_2', ...]
{
data: {
owner: "Me",
user: "My Friend",
},
},
{
// Required for background/quit data-only messages on iOS
contentAvailable: true,
// Required for background/quit data-only messages on Android
priority: "high",
}
);
You can use other methods as well, just make sure that FCM doesnt include notification and is data only.

Alert is not displayed....When clicking on push notifications

I am running sample application..... I am using this module for push notifications..... My problem is when clicking on push notifications after clearing the instance of the app...In onNotification() console is printed but the alert is not displayed.... even try to keep time out for the alert but it doesn't work..... this is a problem is getting for the only iOS....... Please give any suggestions.......
onNotification: notification => {
console.log('NOTIFICATION:', notification)
if(notification.notificationType === XXX){
alert('NOTIFICATION:'+JSON.stringify(notification))
}
}

react native push notification that can be removed after button click

I am using react native v0.45.1.
How can I add to my application notification (no matter if the app is in the background or foreground) that the user can remove only after click an acknowledge button.
I don't want the user to swipe the notification aside without notice it.
how can it be done?
I am not sure https://github.com/wix/react-native-notifications will do what I need.
Edit
I want to have a notification that will act like:
'USB debugging connected
'Touch to disable USB debugging'
The notification can't be removed unless the user actively do something, in my case it will be 'click' on a button
after a lot of digging the solution I implemented was:
setting repeat interval for the notification.
for android:
repeatType: 'time',
repeatTime: timeSpan,
for iOS:
repeatType: 'minute',
when the user click the notification (decided its not the right approached to add actions - buttons - to notification):
PushNotification.configure({
onNotification: (notification) => {
console.log('NOTIFICATION:', notification);
const clicked = notification.userInteraction;
if (clicked) {
if (Platform.OS === 'ios') {
PushNotification.cancelLocalNotifications({ id: notification.data.id });
} else {
PushNotification.cancelLocalNotifications({ id: notification.id });
}
}
},
});
I am aware that this might not be the exact answer to this question. However,
I was looking for a similar solution earlier; how to remove notifications that hasn't been dismissed or opened by a user.
Sometimes the user might open the application / screen, without clicking on the notification. The notification will still be displayed in that case.
Using React Native with Expo, this is the solution I created for removing old notifications created using their Push Notification API.
import * as Notifications from "expo-notifications";
//...
// Remove notifications that exists for this conversation!
useEffect(() => {
Notifications.getPresentedNotificationsAsync().then(res => {
for (let k in res) {
if (
res[k].request.content.data &&
res[k].request.content.data.screen === "Conversations" &&
res[k].request.content.data.conversationId === conversationId
) {
Notifications.dismissNotificationAsync(res[k].request.identifier);
console.log("removed a notification for this conversation");
}
}
});
}, []);
By using the data sent to the Push Notification API, we can determine which notifications should be removed. in this case all notifications containing a conversationId matching the current value from the route are dismissed.