ScaleRocket/Mobile

Notifications avancées

Notifications push riches avec images, canaux de notification, compteurs de badges et notifications locales programmées.

Notifications avancées

Au-delà des notifications push basiques, ScaleRocket Mobile supporte les notifications riches avec images, les canaux de notification Android, les compteurs de badges et les notifications locales programmées.

Notifications riches

Envoyez des notifications avec images et contenu personnalisé :

import * as Notifications from "expo-notifications";

// Programmer une notification locale riche
await Notifications.scheduleNotificationAsync({
  content: {
    title: "New Message",
    subtitle: "From John Doe",
    body: "Hey, check out this photo from the trip!",
    data: { screen: "/messages/123" },
    attachments: [
      {
        url: "https://example.com/photo.jpg",
        identifier: "photo",
      },
    ],
  },
  trigger: null, // Envoyer immédiatement
});

Canaux de notification (Android)

Android 8+ nécessite des canaux de notification. Créez des canaux pour différents types :

import * as Notifications from "expo-notifications";
import { Platform } from "react-native";

async function setupNotificationChannels() {
  if (Platform.OS !== "android") return;

  await Notifications.setNotificationChannelAsync("messages", {
    name: "Messages",
    importance: Notifications.AndroidImportance.HIGH,
    vibrationPattern: [0, 250, 250, 250],
    lightColor: "#3B82F6",
    sound: "default",
  });

  await Notifications.setNotificationChannelAsync("marketing", {
    name: "Promotions",
    importance: Notifications.AndroidImportance.LOW,
    sound: null,
  });

  await Notifications.setNotificationChannelAsync("alerts", {
    name: "Alerts",
    importance: Notifications.AndroidImportance.MAX,
    sound: "default",
    enableVibrate: true,
  });
}
ImportanceComportement
MAXSon, vibration, affichage tête haute
HIGHSon, vibration
DEFAULTSon
LOWPas de son, apparaît dans le panneau
MINPas de son, pas d'interruption visuelle

Compteur de badges

Mettez à jour le badge de l'icône de l'app :

import * as Notifications from "expo-notifications";

// Définir le compteur de badges
await Notifications.setBadgeCountAsync(5);

// Effacer le compteur de badges
await Notifications.setBadgeCountAsync(0);

// Obtenir le compteur actuel
const count = await Notifications.getBadgeCountAsync();

Effacez le badge quand l'utilisateur ouvre l'app :

// app/_layout.tsx
useEffect(() => {
  Notifications.setBadgeCountAsync(0);
}, []);

Notifications locales programmées

Programmez des notifications pour une livraison future sans serveur :

// Notifier dans 30 minutes
await Notifications.scheduleNotificationAsync({
  content: {
    title: "Reminder",
    body: "Don't forget to complete your profile!",
  },
  trigger: {
    seconds: 30 * 60,
    type: Notifications.SchedulableTriggerInputTypes.TIME_INTERVAL,
  },
});

// Notifier à une date spécifique
await Notifications.scheduleNotificationAsync({
  content: {
    title: "Weekly Report",
    body: "Your weekly summary is ready",
  },
  trigger: {
    weekday: 1, // Lundi
    hour: 9,
    minute: 0,
    type: Notifications.SchedulableTriggerInputTypes.CALENDAR,
    repeats: true,
  },
});

Annuler les notifications programmées

// Annuler une notification spécifique
const id = await Notifications.scheduleNotificationAsync({ ... });
await Notifications.cancelScheduledNotificationAsync(id);

// Annuler toutes les notifications programmées
await Notifications.cancelAllScheduledNotificationsAsync();

Gestionnaires de notifications

Configurez le comportement des notifications quand l'app est au premier plan :

Notifications.setNotificationHandler({
  handleNotification: async () => ({
    shouldShowAlert: true,     // Afficher même quand l'app est ouverte
    shouldPlaySound: true,
    shouldSetBadge: true,
  }),
});

Gestion des taps sur notification

Naviguez vers l'écran pertinent quand une notification est tapée :

import { useEffect } from "react";
import { router } from "expo-router";
import * as Notifications from "expo-notifications";

function useNotificationNavigation() {
  useEffect(() => {
    const subscription = Notifications.addNotificationResponseReceivedListener(
      (response) => {
        const data = response.notification.request.content.data;
        if (data.screen) {
          router.push(data.screen as string);
        }
      }
    );

    return () => subscription.remove();
  }, []);
}

Préférences de notification

Laissez les utilisateurs contrôler quelles notifications ils reçoivent :

function NotificationSettings() {
  const [messages, setMessages] = useState(true);
  const [marketing, setMarketing] = useState(false);

  return (
    <View>
      <View style={styles.row}>
        <Text>Messages</Text>
        <Switch value={messages} onValueChange={setMessages} />
      </View>
      <View style={styles.row}>
        <Text>Promotions</Text>
        <Switch value={marketing} onValueChange={setMarketing} />
      </View>
    </View>
  );
}

Stockez les préférences et envoyez-les à votre backend pour que le serveur n'envoie que les notifications pertinentes.

On this page