How to trigger a callback function when we receive notification from app server through fcm even when the app is Killed? - ionic4

How do i trigger the callback function onMesageReceived() in ionic 4 when app is killed?
Tried sending data message but not worked
var payload = {
notification: {
title: title,
body: body,
},
data: {
questionnaire_id: id,
appointmentID: appointmentID,
is_questionnaire: 'true',
notification_foreground: 'true',
},
};
This is how i am sending notification
I am expecting callback to be triggered when app is closed /Killed

Related

Expo Push Notifications Not Pushing to Physical Device

My application in React Native using Expo was sending notifications beautifully using the code below to all of the tokens stored in Firebase. Now, after I published my app on the Expo.io website, it won't work and won't push any notification to any physical device at all. I have tried to rebuild the project in my local machine and run expo on my phone from my computer, and I console logged the information and all of the expo token information is correct and being pulled correctly. Why are the notifications not pushing now to any physical device? Please help. The try block below executes without error, but why aren't notifications pushing then? My component did mount also calls loadInformation & generateToken, and my render and return just call the sendPushNotif function when the user presses the send notification button.
My this.state.finalArray console logs the following: "Array [
Object {
"body": "test",
"title": "this is a test",
"to": Array [
"ExponentPushToken[.......]",
"ExponentPushToken[........]",
], }, ]"
constructor() {
super()
this.state = {
tokenArray: [],
finalArray: [],
}
}
loadInformation = async () => {
var tokens = []
firebase.database().ref('tokens/`).once('value', snapshot => {
const token = Object.values(snapshot.val());
token.map((item) => {
tokens.push(item.data)
return this.setState({ tokenArray: tokens })
})
})
}
generateToken = async () => {
this.state.finalArray = []
this.state.finalArray.push({
to: this.state.tokenArray,
title: this.state.title,
body: this.state.notification
})
}
sendPushNotification = async () => {
//these functions load all the token info from firebase and stores it into an array
this.loadInformation();
this.generateToken();
try {
let response = await fetch("https://exp.host/--/api/v2/push/send", {
method: "POST",
headers: {
Accept: "application/json",
"Accept-encoding": "gzip, deflate",
"Content-Type": "application/json",
},
body: JSON.stringify(this.state.finalArray), //final array has all the tokens and title and body info for the notif. i console logged this and it outputs the correct info
});
alert("Your notification was sent!");
} catch (error) {
console.log(error);
alert("Error! Your notification was not sent.");
}
};
The tokens you have in this.state.finalArray are Expo Push token which every Expo Go app has. So it will not work in Production as every device has its own devicePushToken.
ExponentPushToken[........] tokens work only on Expo Go App and not in Production. See this
Here is the Answer
As expo handle the notification registration for IOS but for android you have to register your app with firebase
So you have to register your app with firebase for this
Click here to get full information
https://docs.expo.dev/push-notifications/using-fcm/
all steps are mentioned
OR for Video information Click here
https://www.youtube.com/watch?v=oRNwNintDW0

React native remote notification

I am trying to send a mobile push notification to my android device based on apex trigger, and I didn't see notification banner but in console I can see onNotification event fired and I can see my payload info.
I have followed In react native app react-native-push-notification library, all changes are done as per the document mention here https://www.npmjs.com/package/react-native-push-notification.
updated MobilePushServiceDevice whenever user open the with token and service type
On FCM created the project and follow this document https://firebase.google.com/docs/cloud-messaging/android/client
Salesforce create connected enable push notification added server key
here is react code
const notification = PushNotification.configure({
// (optional) Called when Token is generated (iOS and Android)
onRegister: function (token) {
//Send this token to salesforce
let createPayload = {
ServiceType: getSystemName() == 'Android' ? 'androidGcm' : 'apple',
ConnectionToken: token.token
};
// register device with salesforce
},
// (required) Called when a remote is received or opened, or local notification is opened
onNotification: function (notification) {
console.log("NOTIFICATION:", notification);
notification.finish(PushNotificationIOS.FetchResult.NoData);
},
// (optional) Called when Registered Action is pressed and invokeApp is false, if true onNotification will be called (Android)
onAction: function (notification) {
console.log("ACTION:", notification.action);
console.log("NOTIFICATION:", notification);
// process the action
},
// (optional) Called when the user fails to register for remote notifications. Typically occurs when APNS is having issues, or the device is a simulator. (iOS)
onRegistrationError: function (err) {
console.error(err.message, err);
},
// IOS ONLY (optional): default: all - Permissions to register.
permissions: {
alert: true,
badge: true,
sound: true,
},
visibility: 'public',
// Should the initial notification be popped automatically
// default: true
popInitialNotification: true,
senderID: "1019984307481",
requestPermissions: true,
});
here is my apex code
`Messaging.PushNotification msg = new Messaging.PushNotification();
Map<String, Object> androidPayload = new Map<String, Object>();
Set<String> userSet = new Set<String>();
androidPayload.put('title', idVSnickname.get(cbuId)+' assigned you a task');
androidPayload.put('message', subject);
androidPayload.put('parentId', str[4].trim());
androidPayload.put('id', str[0].trim());
userSet.add(accIdVSuserId.get(accId));
msg.setPayload(androidPayload);
msg.send('Mimit', userSet);`

Getting double notification popup for single event on ios when sending notification using FCM

Issue Description::
I am working on react native application and using react native firebase messaging service for push notification. I am having a problem on IOS platform. I am getting double notification popups for single event.
Steps I am following to generate the case::
After app installation if I am login and sending notification through FCM I just received a single popup. After this I logged out and login again, now this time I got double popups for single notification. In this case I am not clearing an app from background.
If after every logout I am clearing an app from background I just received a single popup for single event.
When I am logged out from the application, and forcefully sending notification from FCM, I am getting double popup on app initialization screen(login screen).
I am generating a new device token when user login and saving this token inside local storage, we are clearing local storage data on logout.
Code::
async mountDashboard() {
const enabled = await firebase.messaging().hasPermission();
if (enabled) {
const fcmToken = await firebase.messaging().getToken();
await AsyncStorage.setItem(LocalStorageKeys.DEVICE_TOKEN, fcmToken);
if (fcmToken) {
//--- here we are saving our token and sendind data to API
}
}
// in Foreground
this.notificationListener = firebase.notifications().onNotification((notification) => {
new RegisterLocalNotification(notification);
});
// App in Foreground and background
let notificationHandler = new NotificationsHandler();
this.notificationOpenedListener = firebase.notifications().onNotificationOpened((notificationOpen) => {
notificationHandler.handleNotification(notificationOpen.notification);
});
// app close notification handler
AppCloseNotificationHandler.getInstance().handleNotification();
}
componentDidMount() {
this.mountDashboard();
}
Environment::
Binaries:
Node: 10.15.0 - /usr/local/opt/node#10/bin/node
Yarn: 1.10.1 -/usr/local/bin/yarn
npm: 6.4.1 - /usr/local/opt/node#10/bin/npm
Watchman: 4.9.0 - /usr/local/bin/watchman
List item
npm Packages:
react: ^16.8.4 => 16.8.4
react-native: ^0.58.6 => 0.58.6
npm Global Packages:
react-native-cli: 2.0.1
react-native-firebase: 5.2.3
You have to unsubscribe from your listener when the component will unmount. If you don't do that you are subscribing two listeners.
componentWillUnmount() {
this.notificationListener(); // it's unsubscribing your listener
}
Make sure to send this payload via backend, I am using firebase admin SDK.
This will disable Notification By OS and trigger the local notification. I am using this package for local notification https://github.com/zo0r/react-native-push-notification
async function sendPushNotification(message) {
try {
await admin.messaging().sendToDevice(
['dCk27uEySymSdP_vA1C_QI:APA91bEZNyipZDjTLq0jrGnD0qcpKH2y3oTYg3GMgT0pSENNlJEiymOYXvxvnqTFtQaidDLt5KUgp4oDZsfLsQvfiVkL7m1bpMjekHsm-7x1ZDju4TYUMUZeUgYb0CyPwMhdr9RyzA1v'],
{
data: {
owner: 'a',
user: 'a',
},
},
{
// Required for background/quit data-only messages on iOS
contentAvailable: true,
// Required for background/quit data-only messages on Android
priority: 'high',
},
);
console.log('A');
}catch(e) {
console.log('Gagal mengirim pesan');
}
}
And this my code inside App.js that listen to the notification
RNFirebase.onMessage(RNFirebaseOnMessageHandler);
RNFirebase.setBackgroundMessageHandler(RNFirebaseOnMessageHandler);
And inside the handler, I use this
PushNotification.createChannel(
{
channelId: CHANNEL_ID,
channelName: CHANNEL_NAME,
channelDescription: CHANNEL_DESCRIPTION,
soundName: CHANNEL_SOUND,
importance: CHANNEL_IMPORTANCE,
vibrate: CHANNEL_VIBRATE,
},
(created) => console.log(`createChannel returned '${created}'`), // (optional) callback returns whether the channel was created, false means it already existed.
);
PushNotification.localNotification({
channelId: CHANNEL_ID,
// #todo get ticker value from data payload
ticker: 'CreateOrderLandingScreen',
showWhen: true,
autoCancel: true,
largeIcon: CHANNEL_LARGE_ICON,
smallIcon: CHANNEL_SMALL_ICON,
bigText: 'aaaaa',
subText: CHANNEL_SUB_TEXT,
color: Colors.RED,
vibrate: true,
vibration: 300,
priority: 'high',
visibility: 'private',
invokeApp: true,
alertAction: 'view',
id: 0,
title:'aa',
message: 'aaaa',
userInfo: {},
playSound: false,
soundName: 'default',
});

react-native-fcm don't receive notification when app is opened

Why can't i receive notication from react-native-fcm when the app is opened?
Here is my payload
const proState={};
proState.notiUID=recKey;
proState.notiPayload={
data: {
senderKey:senderKey,
id: senderKey+':chat',
type: 'chat'
},
notification: {
title: proState.senderSnap.fullname,
body: proState.lastmsg,
sound: 'default',
id: senderKey+':chat',
tag : senderKey+':chat',
priority : "high",
data: senderKey
},
};
const optionss = {
priority: "high",
show_in_foreground: true
};
return admin.messaging()
.sendToTopic(proState.notiUID, proState.notiPayload,optionss)
I only receives notifications when the app is minimized or closed
you are facing same issue in android and ios both platforms? If you are facing this issue only in ios then don't worry ios not receives notifications in foreground. Which is default behaviour of ios.

How to receive react native push notification in foreground and background

Im using
React Native Push Notification https://github.com/zo0r/react-native-push-notification
Currently, it will receive push notification after closing the app.
How can I pass my pushMessage(chat) into the notification?
How to make it receive push notification in foreground (when the app still open) and background (without opening the app) *currently it will receive the notification after closing the app
which part should I work on?
App.js
--------
PushNotification.configure({
// (required) Called when a remote or local notification is opened or received
onNotification: function(notification) {
console.log( 'NOTIFICATION:', notification );
// process the notification . * this will overwrite the My Notification 1 below
PushNotification.localNotification({
foreground: true,
title: "My Notification Title",
message: "My Notification 2", // (required)
});
// required on iOS only (see fetchCompletionHandler docs: https://facebook.github.io/react-native/docs/pushnotificationios.html)
notification.finish(PushNotificationIOS.FetchResult.NoData);
},
});
class App extends Component{
componentDidMount(){
const connection = signalr.hubConnection('https://api.abc.com');
const proxy = connection.createHubProxy('chatHub');
proxy.on('pushMessage', (chat) => {
PushNotification.localNotification({
foreground: true,
title: "My Notification Title",
message: "My Notification 1", // (required)
});
});
}
}