how to set small Icon when pushing message in nodejs - firebase-cloud-messaging

I'm usnig fcm for notification in nodejs. So I made this And when I push message from nodejs to android, I got message well. When the app is running, I can get the small Icon image. But when the app is not running, I got the notification with no image. how can I get the push message with image when the app is in background? here is my nodejs code
let pushMsg = req.body.pushMsg;
let groupName = req.body.groupName;
console.log(groupName)
var condition = "'"+groupName+"' in topics"; //"'all' in topics || 'industry-tech' in topics";
var message = {
notification: {
title: 'schedule updated',
body: pushMsg,
image:'./upload/haiilogo.png'
},
condition: condition
};
admin.messaging().send(message)
.then((response) => {
console.log('Successfully sent message:', response);
})
.catch((error) => {
console.log('Error sending message:', error);
});

I solved. I added manifest to default icon like this
<meta-data android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="#drawable/haiilogo" />

Related

react-native, Android Freshchat isFreshchatNotification not handling firebase remote message

I'm trying to integrate react-native-freshchat-sdk to react native app, but when firebase remote message is coming, freshchatNotification is 0, but it should be 1. Even if I pass notification to Freshchat.handlePushNotification nothing happens. I assume Freshchat.handlePushNotification should navigate the user to the conversation
Actual result
freshchatNotification is 0 if it is fcm notification
Freshchat.handlePushNotification(notification) does nothing
Expected result:
freshchatNotification should be equal 1 if it is fcm notification
Freshchat.handlePushNotification(notification) should navigate the user to the chat
import messaging from '#react-native-firebase/messaging'
import { Freshchat} from 'react-native-freshchat-sdk'
//...
useEffect(() => {
const unsubscribe = messaging().onMessage(notification => {
Freshchat.isFreshchatNotification(notification, (freshchatNotification) => {
Freshchat.handlePushNotification(notification);
if (freshchatNotification) {
Freshchat.handlePushNotification(notification);
} else {//...}
})
});
return unsubscribe
}, [])
See push notification payload below:
Faced similar issue, worked by passing notification.data instead of direct notification object to Freshchat
useEffect(() => {
const unsubscribe = messaging().onMessage(notification => {
Freshchat.isFreshchatNotification(notification.data, (freshchatNotification) => {
Freshchat.handlePushNotification(notification);
if (freshchatNotification) {
Freshchat.handlePushNotification(notification.data);
} else {//...}
})
});
return unsubscribe
}, [])

Send push notification using Expo

I am trying to send push notification using Expo, and I receive it. But there is no vibrate or sound and no pop up as well on my device. I am using Galaxy S9 with Android 9. I have not tried on Iphone yet.
Push notification is sent by nodejs and the user who installed the app will receive the push notification. User expo token is saved in firebase database. I succeed to save and fetch the token.
Below is from expo app
class App extends Component {
componentWillMount() {
firebase.initializeApp(config);
this.registerForPushNotificationsAsync();
}
async registerForPushNotificationsAsync(){
const { status: existingStatus } = await Permissions.getAsync(
Permissions.NOTIFICATIONS
);
let finalStatus = existingStatus;
if (Platform.OS === 'android') {
Notifications.createChannelAndroidAsync('chat-messages', {
name: 'Chat messages',
sound: true,
priority: 'high', // was max
vibrate: [0, 250, 250, 250],
});
}
if (existingStatus !== 'granted') {
const { status } = await Permissions.askAsync(Permissions.NOTIFICATIONS);
finalStatus = status;
}
Below is from nodejs server-side
function sendMessage(to, title, body) {
const expo = new Expo();
let messages = [];
messages.push({
to, // Expo user token
body,
data: { withSome: 'data' },
ios: {
sound: true
},
android: {
"channelId": "chat-messages" //and this
}
})
let chunks = expo.chunkPushNotifications(messages);
let tickets = [];
(async () => {
for (let chunk of chunks) {
try {
let ticketChunk = await expo.sendPushNotificationsAsync(chunk);
tickets.push(...ticketChunk);
} catch (error) {
console.error(error);
}
}
})();
}
Also could we redirect to web page when user click the push notification?
I see three problems on your backend code ( expo push notification docs for reference https://docs.expo.io/versions/latest/guides/push-notifications/):
According to the docs, there should be no ios or android properties on the request body;
sound should be either 'default' or null, instead of true;
You created the notification channel on the device, but when you send the notification, you forgot to tell which channel you are sending to.
All that said, your code that calls the expo push notifications api should look something like this:
messages.push({
to, // Expo user token
title: 'some title', //it is good practice to send title, and it will look better
body,
data: { withSome: 'data' },
priority: 'high', //to make sure notification is delivered as fast as possible. see documentation for more details
sound: true, //for iOS devices and android below 8.0
channelId: 'chat-messages', //for devices on android 8.0 and above
})
I hope this helps.

Unable to get push notification from fcm in react native

I am getting push notification from firebase but when I sent it using the "https://fcm.googleapis.com/fcm/send" on android in react native using react-native-firebase library, I do not get any notification on android. However I am able to display the message on the console using "onMessage" method. But how I can get notification in the notification bar. My message is data-only therefore I also created bgMessaging.js for handling background message and here also I am able to display message on console but not on notification.
How I can fix this issue and display the message on the notification bar with data-only messages.
Below is my code
bgMessaging.js
import firebase from 'react-native-firebase';
// Optional flow type
import type { RemoteMessage } from 'react-native-firebase';
export default async (message: RemoteMessage) => {
// handle your message
console.log("message")
console.log(message)
// senName = message.data.senderName;
// senUid = message.data.senderUid;
// const notification = new
// firebase.notifications.Notification()
// .setNotificationId('notificationId')
// .setTitle(message.data.title)
// .setBody(message.data.body)
// .android.setChannelId('channel_id_foreground')
// .android.setSmallIcon('ic_launcher');
// firebase.notifications().displayNotification(notification);
return Promise.resolve();
}
index.js(following lines added at the end)
AppRegistry.registerHeadlessTask('RNFirebaseBackgroundMessage', () => bgMessaging); // <-- Add this line
App.js
componentDidMount() {
this.messageListener = firebase.messaging().onMessage((message: RemoteMessage) => {
//process data message
console.log(message);
});
}
AndroidManifest.xml
<service android:name="io.invertase.firebase.messaging.RNFirebaseBackgroundMessagingService" />
<service android:name="io.invertase.firebase.messaging.RNFirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<service android:name="io.invertase.firebase.messaging.RNFirebaseInstanceIdService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
</intent-filter>
</service>
<service android:name=".MyTaskService" />
I've had the exact same problem, I've received the data-only messages but couldn't display the notification.
I found out that in order to display notifications for 8+ Android Version you need to create an Android Channel first, Code:
// Create Channel first.
const channel = new firebase.notifications.Android.Channel(
"general-channel",
"General Notifications",
firebase.notifications.Android.Importance.Default
).setDescription("General Notifications");
firebase.notifications().android.createChannel(channel);
// Build your notification
const notification = new firebase.notifications.Notification()
.setTitle(...)
.setBody(...)
.setNotificationId("notification-action")
.setSound("default")
.setData(message.data)
.android.setChannelId("general-channel")
.android.setPriority(firebase.notifications.Android.Priority.Max);
// Display the notification (with debug)
firebase
.notifications()
.displayNotification(notification)
.catch(err => console.error(err));
You can also do things when the notification is displayed:
firebase.notifications().onNotificationDisplayed(notification => { ... })
Or when it is received by the phone:
firebase.notifications().onNotification(notification => { ... })
If you want to get the notification that triggered the app opening, use the following:
firebase.notifications().getInitialNotification().then(notification => { ... })
refer the document here https://rnfirebase.io/docs/v4.3.x/notifications/receiving-notifications
App.js
async componentDidMount() {
this.getToken();
this.createNotificationListeners();
}
async createNotificationListeners() {
this.notificationListener = firebase.notifications().onNotification((notification) => {
const { title, body, data } = notification;
notification
.android.setChannelId('channel')
.android.setSmallIcon('icon')
.android.setAutoCancel(true)
.android.setPriority(firebase.notifications.Android.Priority.Max)
.setSound('default');
firebase.notifications().displayNotification(notification);
});
}
Firebase v6 will not show notification when the app is in foreground state
refer to this: https://rnfirebase.io/messaging/usage
You can use 3rd party libraries like react-native-push-notification. In react-native-push-notification, you need to create a channel first. Please follow this documentation
https://github.com/zo0r/react-native-push-notification#channel-management-android
After the channel created, include it when you want to show the notification. Like This:
import messaging from '#react-native-firebase/messaging';
...
messaging().onMessage(async (remoteMessage) => {
console.log('Auth.js / Message handled in app!', remoteMessage)
PushNotification.localNotification({
message: remoteMessage.notification.body,
title: remoteMessage.notification.title,
bigPictureUrl: remoteMessage.notification.android.imageUrl,
smallIcon: remoteMessage.notification.android.imageUrl,
channelId: 'channel-id',
});
});

How to receive firebase push notification in react native IOS?

Is there a way on how to receive push notification payload in IOS? In android it works by doing it this way:
firebase.messaging().onMessage((message: RemoteMessage) => {
// Process your message as required
});
however it does not work in ios. It tried:
firebase.notifications().displayNotification((notification) => {
console.log(notification);
});
or
firebase.notifications().onNotification((notification) => {
console.log(notification);
});
still nothing works. Thanks
Nevermind, I sorted it out by call it this way:
firebase.notifications().onNotificationDisplayed((notification: Notification) => {
console.log(notification);
});
firebase.notifications().onNotification((notification: Notification) => {
console.log(notification);
});

How to bring app to foreground from background in Ionic 2?

Is there any possible way to bring app from background mode in to foreground when an event happens like notification arrive? like WhatsApp and Skype that bring into foreground when a voice call or video call arrive.
Update:
public subscribeToPushNotificationEvents(): void {
// Handle token refresh
this.firebase.onTokenRefresh().subscribe(
token => {
//console.log(`The new token is ${token}`);
this.saveToken(token);
},
error => {
console.error('Error refreshing token', error);
});
// Handle incoming notifications
this.firebase.onNotificationOpen().subscribe(
(notification: NotificationModel) => {
this.backgroundMode.moveToForeground();
let notificationAlert = this.alertCtrl.create({
title: notification.title,
message: notification.body,
buttons: ['Ok']
});
notificationAlert.present();
}
As far as I know, your only option is this plugin: http://ionicframework.com/docs/native/background-mode/