Es werden nur zwei Benachrichtigungen im Vordergrund angezeigt
Posted: 07 Jan 2025, 06:42
Ich verwende Firebase Cloud Messaging (FCM), um reine Datennachrichten in meiner React Native-App zu senden. Wenn jedoch eine Benachrichtigung im Vordergrund empfangen wird, erhalte ich zwei Benachrichtigungen im Handler.
Ich erhalte zwei Benachrichtigungen sowohl in Android als auch in iOS. Ich verwende Firebase Messaging und Notifee zum Anzeigen der Benachrichtigungen.
Code: Select all
const getFCMToken = async () => {
try {
let fcmToken = await AsyncStorage.getItem('fcmToken');
console.log('******** fcmToken 1', fcmToken);
if (!fcmToken) {
// Get the FCM token
fcmToken = await messaging().getToken();
await AsyncStorage.setItem('fcmToken', fcmToken);
}
let data = { fcm_token: fcmToken };
console.log('yvguhbijn', data);
let response = await HomeService.postFCMToken(data);
if (response?.data?.success) {
Toast.show('FCM set successfully');
}
} catch (error) {
console.error('Error getting FCM token:', error);
}
};
const displayBgContent = async (remoteMessage) => {
const { data } = remoteMessage;
// Generate a default title and body if not provided
const title = data?.title;
const body = data?.body;
// Safely parse the actions field
let actions = [];
try {
const parsedActions = JSON.parse(data?.actions || '[]'); // Parse or default to an empty array
actions = parsedActions.map((action) => ({
title: action.name.toUpperCase(), // Example: "BUY"
pressAction: {
id: action.name, // Example: "buy"
launchActivity: 'default',
},
}));
} catch (error) {
console.error('Failed to parse actions:', error);
}
// Check if the image URL exists and is valid
const image = data?.image && data.image.trim() !== '' ? data.image : null;
// Display notification using notifee
if (actions.length == 0) {
await notifee.displayNotification({
title,
body,
android: {
channelId: 'default',
smallIcon: 'notification_icon', // Ensure you have this icon in your project
largeIcon: image || 'default_icon', // Fallback to a local image if no valid URL
importance: AndroidImportance.HIGH,
pressAction: {
id: 'default',
},
badge: true,
color: '#FF7900',
onlyAlertOnce: true,
style: image
? {
type: AndroidStyle.BIGPICTURE, // Show a big picture style notification
picture: image,
}
: undefined, // Skip style if no image
},
ios: {
foregroundPresentationOptions: {
badge: true,
sound: true,
banner: true,
list: true,
},
categoryId: 'customCategory', // Match the category ID registered earlier
sound: 'default', // Notification sound
attachments: image
? [
{
url: image, // Attach image only if it exists
},
]
: [], // Empty array if no image
},
data, // Include the original payload for further handling
});
} else {
await notifee.displayNotification({
title,
body,
android: {
channelId: 'default',
smallIcon: 'notification_icon', // Ensure you have this icon in your project
largeIcon: image || 'default_icon', // Fallback to a local image if no valid URL
importance: AndroidImportance.HIGH,
actions: actions, // Attach dynamic actions
badge: true,
color: '#FF7900',
onlyAlertOnce: true,
style: image
? {
type: AndroidStyle.BIGPICTURE, // Show a big picture style notification
picture: image,
}
: undefined, // Skip style if no image
},
ios: {
foregroundPresentationOptions: {
badge: true,
sound: true,
banner: true,
list: true,
},
categoryId: 'customCategory', // Match the category ID registered earlier
sound: 'default', // Notification sound
attachments: image
? [
{
url: image, // Attach image only if it exists
},
]
: [], // Empty array if no image
},
data, // Include the original payload for further handling
});
}
};
const listenToInAppNotifications = async () => {
const unsubscribe = messaging().onMessage(async (remoteMessage) => {
await displayBgContent(remoteMessage);
const { messageId } = remoteMessage;
if (!messageId) {
return;
}
// Cancel the notification after displaying it
try {
await notifee.cancelNotification(messageId);
console.log(`Notification with ID ${messageId} canceled successfully`);
} catch (error) {
console.error(
`Failed to cancel notification with ID ${messageId}:`,
error,
);
}
});
return unsubscribe;
};