Inicio > Cursos > React Native > Notificaciones Push
React NativeAPIs Nativas y ExpoLección 11 de 14

Notificaciones Push

Las notificaciones en mobile son de dos tipos: locales y push. Las notificaciones locales se disparan desde el código de la app sin servidor: recordatorios, alarmas, completar una tarea de fondo. Las notificaciones push llegan desde un servidor externo al dispositivo incluso cuando la app está cerrada: mensajes, alertas de precio, noticias. Para notificaciones push cada dispositivo tiene un token único que obtienes con Notifications.getExpoPushTokenAsync().

El servicio de Expo Push simplifica enormemente las notificaciones push: en lugar de manejar separadamente APNS (Apple Push Notification Service) y FCM (Firebase Cloud Messaging), envías una petición al servidor de Expo con el token del dispositivo y el mensaje, y Expo se encarga del resto.

Para producción, guardas los tokens en tu base de datos y cuando necesitas notificar a un usuario, buscas su token y envías la notificación. iOS requiere aprobación del usuario; Android las permite por defecto.

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

// Configurar comportamiento de notificaciones
Notifications.setNotificationHandler({
  handleNotification: async () => ({
    shouldShowAlert: true,
    shouldPlaySound: true,
    shouldSetBadge: false,
  }),
});

// Registrar para notificaciones push
async function registrarNotificaciones() {
  if (!Device.isDevice) {
    alert("Notificaciones solo en dispositivo real");
    return null;
  }

  const { status: existente } = await Notifications.getPermissionsAsync();
  let estado = existente;

  if (existente !== "granted") {
    const { status } = await Notifications.requestPermissionsAsync();
    estado = status;
  }

  if (estado !== "granted") {
    alert("Permiso de notificaciones denegado");
    return null;
  }

  // Token de push (único por dispositivo)
  const token = await Notifications.getExpoPushTokenAsync({
    projectId: "tu-project-id"
  });

  // En Android necesitas canal de notificación
  if (Platform.OS === "android") {
    await Notifications.setNotificationChannelAsync("default", {
      name: "default",
      importance: Notifications.AndroidImportance.MAX,
      vibrationPattern: [0, 250, 250, 250],
    });
  }

  return token.data;
}

// Notificación local (sin servidor)
async function enviarNotificacionLocal() {
  await Notifications.scheduleNotificationAsync({
    content: {
      title: "¡Recordatorio!",
      body: "Tienes una tarea pendiente",
      data: { pantalla: "Tareas" },
    },
    trigger: { seconds: 5 }, // En 5 segundos
  });
}
Consejo📬 Para notificaciones push reales, envías el Expo Push Token a tu servidor. Tu servidor usa la API de Expo para enviar notificaciones a dispositivos específicos.
← GPS y UbicaciónNetworking y APIs REST →

Practica esta lección

Resuelve los ejercicios del curso de React Native en la app, gratis y con corrección automática.

Empezar a practicar