Cours React Native · Module 7: Notifications

expo-notifications - Introduction

2 min de lecture ·
Dans cette leçon3

Bienvenue à la Tour des Sirènes ! Ici, tu vas apprendre à envoyer des notifications - comme des sirènes qui appellent les habitants de l'Atlantide.

Installation

npx expo install expo-notifications expo-device expo-constants

Configuration (app.json)

{
  "expo": {
    "plugins": [
      [
        "expo-notifications",
        {
          "icon": "./assets/notification-icon.png",
          "color": "#1a5276",
          "sounds": ["./assets/sounds/notification.wav"]
        }
      ]
    ],
    "android": {
      "useNextNotificationsApi": true
    }
  }
}

Configuration de base

import * as Notifications from 'expo-notifications';
import * as Device from 'expo-device';
import { Platform } from 'react-native';

// Configure comment afficher les notifications quand l'app est active
Notifications.setNotificationHandler({
  handleNotification: async () => ({
    shouldShowBanner: true,
    shouldShowList: true,
    shouldPlaySound: true,
    shouldSetBadge: true,
  }),
});

// Enregistrement pour les notifications push
async function registerForPushNotificationsAsync() {
  let token;

  // Les notifications push ne fonctionnent que sur de vrais appareils
  if (!Device.isDevice) {
    console.log('Les notifications push nécessitent un appareil physique');
    return;
  }

  // Vérifier / demander les permissions
  const { status: existingStatus } = await Notifications.getPermissionsAsync();
  let finalStatus = existingStatus;

  if (existingStatus !== 'granted') {
    const { status } = await Notifications.requestPermissionsAsync();
    finalStatus = status;
  }

  if (finalStatus !== 'granted') {
    console.log('Pas de permissions de notification');
    return;
  }

  // Récupérer l'Expo Push Token
  token = await Notifications.getExpoPushTokenAsync({
    projectId: 'your-project-id', // depuis app.json
  });

  // Android : définir le canal de notification
  if (Platform.OS === 'android') {
    await Notifications.setNotificationChannelAsync('default', {
      name: 'default',
      importance: Notifications.AndroidImportance.MAX,
      vibrationPattern: [0, 250, 250, 250],
      lightColor: '#1a5276',
    });
  }

  return token;
}

expo-notifications est la bibliothèque officielle d'Expo pour gérer les notifications !

Code de cette leçon : App.tsx
import { useEffect, useState } from 'react';
import { View, Text, Button, StyleSheet, Platform } from 'react-native';
import * as Notifications from 'expo-notifications';
import * as Device from 'expo-device';

// Configure l'affichage des notifications quand l'application est au premier plan
Notifications.setNotificationHandler({
  handleNotification: async () => ({
    shouldShowAlert: true,
    shouldPlaySound: true,
    shouldSetBadge: true,
  }),
});

// Enregistrement pour obtenir un Expo Push Token
async function registerForPushNotificationsAsync(): Promise<string | undefined> {
  // Les notifications push ne fonctionnent que sur un appareil physique
  if (!Device.isDevice) {
    console.log('Push requires a physical device');
    return;
  }

  // TODO : vérifie les permissions actuelles avec Notifications.getPermissionsAsync()
  const { status: existingStatus } = await Notifications.getPermissionsAsync();
  let finalStatus = existingStatus;

  // TODO : si non accordées, demande les permissions avec requestPermissionsAsync()
  if (existingStatus !== 'granted') {
    // const { status } = ...
  }

  if (finalStatus !== 'granted') {
    console.log('No notification permissions');
    return;
  }

  // TODO : récupère le token avec Notifications.getExpoPushTokenAsync()
  const token = '';

  // TODO (Android) : configure le canal 'default' avec setNotificationChannelAsync
  if (Platform.OS === 'android') {
    // await Notifications.setNotificationChannelAsync('default', { ... });
  }

  return token;
}

export default function App() {
  const [pushToken, setPushToken] = useState<string>('');

  useEffect(() => {
    registerForPushNotificationsAsync().then((token) => {
      if (token) setPushToken(token);
    });
  }, []);

  return (
    <View style={styles.container}>
      <Text style={styles.title}>Tour des Sirènes</Text>
      <Text style={styles.token}>{pushToken || 'Aucun token'}</Text>
      <Button title="Enregistrer les notifications" onPress={() => registerForPushNotificationsAsync()} />
    </View>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#1a5276', padding: 20 },
  title: { fontSize: 24, color: '#fff', marginBottom: 16 },
  token: { fontSize: 12, color: '#aed6f1', marginBottom: 16, textAlign: 'center' },
});

Entrées de la documentation utilisées dans cette leçon

Tu as repéré une erreur dans cette leçon ?

Teste tes connaissances

Réponds aux questions de cette leçon. Choisis une réponse pour voir tout de suite si elle est correcte.

  1. 1. Comment installer expo-notifications ?

  2. 2. Que configure Notifications.setNotificationHandler ?

Voici 2 des 4 questions de cette leçon. Réponds aux autres dans le jeu.

Tâches pratiques dans le jeu

  • Tri vertical

    Ordonne la configuration du handler de notifications :

  • Tri horizontal

    Ordonne la récupération du token push :

  • Éditeur de code

    Complète le code d'enregistrement du token push.

Articles utiles