Получение двух уведомлений только на переднем планеJavascript

Форум по Javascript
Ответить
Anonymous
 Получение двух уведомлений только на переднем плане

Сообщение Anonymous »

Я использую Firebase Cloud Messaging (FCM) для отправки сообщений, содержащих только данные, в моем приложении React Native. Однако когда уведомление получено на переднем плане, я получаю два уведомления в обработчике.

Код: Выделить всё

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;
};
Получение двух уведомлений на Android и iOS. Для отображения уведомлений я использую Firebase Messaging и Notifee.


Подробнее здесь: https://stackoverflow.com/questions/793 ... round-only
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Javascript»