Envía mensajes a varios dispositivos en plataformas de Apple

Firebase Cloud Messaging ofrece dos maneras de enviar un mensaje a múltiples dispositivos:

  • Los mensajes por tema, que permiten enviar un mensaje a varios dispositivos que hayan aceptado un tema específico.
  • Los mensajes por grupos de dispositivos, que te permiten enviar un mensaje a varias instancias de una app que se ejecute en varios dispositivos de un grupo.

Este instructivo se enfoca en el envío de mensajes por temas desde el servidor de apps mediante el SDK de Admin o la API de REST para FCM, así como en la recepción y administración de ellos en una app de Apple. En esta página, se indican todos los pasos necesarios para lograrlo, desde la configuración hasta la verificación. Es posible que ya hayas realizado algunos de los pasos si configuraste una app cliente en Apple para FCM o si completaste los pasos para enviar tu primer mensaje.

Agrega Firebase a tu proyecto de Apple

Es posible que hayas completado tareas que aparecen en esta sección si ya habilitaste otras funciones de Firebase para tu app. En el caso específico de FCM, deberás subir tu clave de autenticación de APNS y registrarte para habilitar las notificaciones remotas.

Requisitos

  • Instala lo siguiente:

    • Xcode 14.1 o una versión posterior
  • Asegúrate de que tu proyecto cumpla con estos requisitos:

    • Se debe seleccionar como objetivo a estas versiones de las plataformas o a otras más recientes:
      • iOS 11
      • macOS 10.13
      • tvOS 12
      • watchOS 6
  • Configura un dispositivo Apple físico para ejecutar tu app y completa las siguientes tareas:

    • Obtén una clave de autenticación de notificaciones push de Apple para tu cuenta de Apple Developer.
    • En Xcode, habilita las notificaciones push en App > Capabilities.

Si solo quieres probar un producto de Firebase, pero aún no tienes un proyecto de Xcode, puedes descargar una de estas muestras de inicio rápido.

Crea un proyecto de Firebase

Antes de que puedas agregar Firebase a tu app para Apple, debes crear un proyecto de Firebase y conectarlo a ella. Visita Información sobre los proyectos de Firebase para obtener más detalles sobre este tema.

Registra tu app en Firebase

Si quieres usar Firebase en tu app para Apple, debes registrar la app en el proyecto de Firebase. El registro de tu app a menudo se conoce como “agregar” la app a tu proyecto.

  1. Dirígete a Firebase console.

  2. En el centro de la página de descripción general del proyecto, haz clic en el ícono de iOS+ para iniciar el flujo de trabajo de configuración.

    Si ya agregaste una app a tu proyecto de Firebase, haz clic en Agregar app para que se muestren las opciones de plataforma.

  3. Ingresa el ID del paquete de la app en el campo ID del paquete.

  4. Ingresa otra información, como el Sobrenombre de la app y el ID de App Store (opcional).

  5. Haz clic en Registrar app.

Agrega un archivo de configuración de Firebase

  1. Haz clic en Descargar GoogleService-Info.plist a fin de obtener el archivo de configuración de Firebase para plataformas de Apple (GoogleService-Info.plist).

  2. Traslada el archivo de configuración al directorio raíz de tu proyecto de Xcode. Si se te solicita, selecciona la opción para agregar el archivo de configuración a todos los destinos.

Si tienes múltiples IDs de paquete en tu proyecto, debes asociar cada uno de ellos a una app registrada en Firebase console para que cada app tenga su propio archivo GoogleService-Info.plist.

Agrega los SDK de Firebase a tu app

Usa Swift Package Manager para instalar y administrar las dependencias de Firebase.

  1. En Xcode, con tu proyecto de app abierto, navega a File > Add Packages.
  2. Cuando se te solicite, agrega el repositorio del SDK de Firebase para plataformas de Apple:
  3.   https://github.com/firebase/firebase-ios-sdk
  4. Elige la biblioteca de Firebase Cloud Messaging.
  5. Para obtener una experiencia óptima con Firebase Cloud Messaging, te recomendamos habilitar Google Analytics en tu proyecto de Firebase y agregar el SDK de Firebase para Google Analytics a la app. Puedes seleccionar la biblioteca sin la colección de IDFA o con la colección de IDFA.
  6. Cuando termines, Xcode comenzará a resolver y descargar automáticamente tus dependencias en segundo plano.

Sube tu clave de autenticación de APNS

Sube la clave de autenticación de APNS a Firebase. Si aún no tienes una, asegúrate de crearla en el Centro para miembros de Apple Developer.

  1. Dentro del proyecto en Firebase console, selecciona el ícono de ajustes, elige Configuración del proyecto y, luego, la pestaña Cloud Messaging.

  2. En Clave de autenticación de APNS, en iOS app configuration, haz clic en el botón Subir.

  3. Busca la ubicación en la que guardaste la clave, selecciónala y haz clic en Abrir. Agrega el ID de clave correspondiente (disponible en el centro para miembros de Apple Developer) y haz clic en Subir.

Inicializa Firebase en la app

Debes agregar el código de inicialización de Firebase a tu aplicación. Importa el módulo de Firebase y configura una instancia compartida de la siguiente manera:

  1. Importa el módulo FirebaseCore en tu UIApplicationDelegate, así como cualquier otro módulo de Firebase que use el delegado de la app. Por ejemplo, para usar Cloud Firestore y Authentication:

    SwiftUI

    import SwiftUI
    import FirebaseCore
    import FirebaseFirestore
    import FirebaseAuth
    // ...
          

    Swift

    import FirebaseCore
    import FirebaseFirestore
    import FirebaseAuth
    // ...
          

    Objective-C

    @import FirebaseCore;
    @import FirebaseFirestore;
    @import FirebaseAuth;
    // ...
          
  2. Configura una instancia compartida de FirebaseApp en el método application(_:didFinishLaunchingWithOptions:) del delegado de la app:

    SwiftUI

    // Use Firebase library to configure APIs
    FirebaseApp.configure()

    Swift

    // Use Firebase library to configure APIs
    FirebaseApp.configure()

    Objective-C

    // Use Firebase library to configure APIs
    [FIRApp configure];
  3. Si usas SwiftUI, debes crear un delegado de la aplicación y adjuntarlo al struct de tu App a través de UIApplicationDelegateAdaptor o NSApplicationDelegateAdaptor. También debes inhabilitar el swizzling del delegado de la app. Para obtener más información, consulta las instrucciones de SwiftUI.

    SwiftUI

    @main
    struct YourApp: App {
      // register app delegate for Firebase setup
      @UIApplicationDelegateAdaptor(AppDelegate.self) var delegate
    
      var body: some Scene {
        WindowGroup {
          NavigationView {
            ContentView()
          }
        }
      }
    }
          

Regístrate para habilitar las notificaciones remotas

Durante el inicio o en el punto que desees del flujo de tu aplicación, registra tu app para habilitar las notificaciones remotas. Llama a registerForRemoteNotifications como se muestra a continuación:

Swift


UNUserNotificationCenter.current().delegate = self

let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
UNUserNotificationCenter.current().requestAuthorization(
  options: authOptions,
  completionHandler: { _, _ in }
)

application.registerForRemoteNotifications()

Objective-C


[UNUserNotificationCenter currentNotificationCenter].delegate = self;
UNAuthorizationOptions authOptions = UNAuthorizationOptionAlert |
    UNAuthorizationOptionSound | UNAuthorizationOptionBadge;
[[UNUserNotificationCenter currentNotificationCenter]
    requestAuthorizationWithOptions:authOptions
    completionHandler:^(BOOL granted, NSError * _Nullable error) {
      // ...
    }];

[application registerForRemoteNotifications];

Suscribe la app cliente a un tema

Las apps cliente se pueden suscribir a cualquier tema existente o pueden crear un tema nuevo. Cuando una app cliente se suscribe a un nombre de tema nuevo (uno que no existe aún para tu proyecto de Firebase), se crea un tema nuevo con ese nombre en FCM y cualquier cliente se puede suscribir a él posteriormente.

Para suscribirte a un tema, llama al método de suscripción desde el subproceso principal de la aplicación (FCM no tiene seguridad en los subprocesos). Si la solicitud de suscripción falla en el inicio, FCM vuelve a intentarlo automáticamente. Cuando la suscripción no se puede completar, esta genera un error que puedes capturar en un controlador de finalización, como se muestra a continuación:

Swift

Messaging.messaging().subscribe(toTopic: "weather") { error in
  print("Subscribed to weather topic")
}

Objective-C

[[FIRMessaging messaging] subscribeToTopic:@"weather"
                                completion:^(NSError * _Nullable error) {
  NSLog(@"Subscribed to weather topic");
}];

Esta llamada realiza una solicitud asíncrona al backend de FCM y suscribe al cliente al tema determinado. Antes de llamar a subscribeToTopic:topic, asegúrate de que la instancia de app cliente ya haya recibido un token de registro mediante la devolución de llamada didReceiveRegistrationToken.

Cada vez que la app se inicia, FCM se asegura de que todos los temas solicitados estén suscritos. Para anular la suscripción, llama a unsubscribeFromTopic:topic; FCM la anulará en segundo plano.

Recibe y administra mensajes a temas

FCM entrega mensajes a temas de la misma manera que otros mensajes downstream.

Implementa application(_:didReceiveRemoteNotification:fetchCompletionHandler:) de la siguiente manera:

Swift

func application(_ application: UIApplication,
                 didReceiveRemoteNotification userInfo: [AnyHashable: Any]) async
  -> UIBackgroundFetchResult {
  // If you are receiving a notification message while your app is in the background,
  // this callback will not be fired till the user taps on the notification launching the application.
  // TODO: Handle data of notification

  // With swizzling disabled you must let Messaging know about the message, for Analytics
  // Messaging.messaging().appDidReceiveMessage(userInfo)

  // Print message ID.
  if let messageID = userInfo[gcmMessageIDKey] {
    print("Message ID: \(messageID)")
  }

  // Print full message.
  print(userInfo)

  return UIBackgroundFetchResult.newData
}

Objective-C

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
    fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
  // If you are receiving a notification message while your app is in the background,
  // this callback will not be fired till the user taps on the notification launching the application.
  // TODO: Handle data of notification

  // With swizzling disabled you must let Messaging know about the message, for Analytics
  // [[FIRMessaging messaging] appDidReceiveMessage:userInfo];

  // ...

  // Print full message.
  NSLog(@"%@", userInfo);

  completionHandler(UIBackgroundFetchResultNewData);
}

Crea solicitudes de envío

Puedes enviar mensajes al tema después de haber creado uno, ya sea mediante la suscripción de instancias de la app cliente al tema desde el cliente o a través de la API del servidor. Si es la primera vez que creas solicitudes de envío para FCM, consulta la guía sobre tu entorno de servidor y FCM para obtener información importante de carácter general y sobre la configuración.

Especifica el nombre que quieres darle al tema en la lógica de envío del backend, como se muestra a continuación:

Node.js

// The topic name can be optionally prefixed with "/topics/".
const topic = 'highScores';

const message = {
  data: {
    score: '850',
    time: '2:45'
  },
  topic: topic
};

// Send a message to devices subscribed to the provided topic.
getMessaging().send(message)
  .then((response) => {
    // Response is a message ID string.
    console.log('Successfully sent message:', response);
  })
  .catch((error) => {
    console.log('Error sending message:', error);
  });

Java

// The topic name can be optionally prefixed with "/topics/".
String topic = "highScores";

// See documentation on defining a message payload.
Message message = Message.builder()
    .putData("score", "850")
    .putData("time", "2:45")
    .setTopic(topic)
    .build();

// Send a message to the devices subscribed to the provided topic.
String response = FirebaseMessaging.getInstance().send(message);
// Response is a message ID string.
System.out.println("Successfully sent message: " + response);

Python

# The topic name can be optionally prefixed with "/topics/".
topic = 'highScores'

# See documentation on defining a message payload.
message = messaging.Message(
    data={
        'score': '850',
        'time': '2:45',
    },
    topic=topic,
)

# Send a message to the devices subscribed to the provided topic.
response = messaging.send(message)
# Response is a message ID string.
print('Successfully sent message:', response)

Go

// The topic name can be optionally prefixed with "/topics/".
topic := "highScores"

// See documentation on defining a message payload.
message := &messaging.Message{
	Data: map[string]string{
		"score": "850",
		"time":  "2:45",
	},
	Topic: topic,
}

// Send a message to the devices subscribed to the provided topic.
response, err := client.Send(ctx, message)
if err != nil {
	log.Fatalln(err)
}
// Response is a message ID string.
fmt.Println("Successfully sent message:", response)

C#

// The topic name can be optionally prefixed with "/topics/".
var topic = "highScores";

// See documentation on defining a message payload.
var message = new Message()
{
    Data = new Dictionary<string, string>()
    {
        { "score", "850" },
        { "time", "2:45" },
    },
    Topic = topic,
};

// Send a message to the devices subscribed to the provided topic.
string response = await FirebaseMessaging.DefaultInstance.SendAsync(message);
// Response is a message ID string.
Console.WriteLine("Successfully sent message: " + response);

REST

POST https://fcm.googleapis.com/v1/projects/myproject-b5ae1/messages:send HTTP/1.1

Content-Type: application/json
Authorization: Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA
{
  "message":{
    "topic" : "foo-bar",
    "notification" : {
      "body" : "This is a Firebase Cloud Messaging Topic Message!",
      "title" : "FCM Message"
      }
   }
}

Comando de cURL:

curl -X POST -H "Authorization: Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA" -H "Content-Type: application/json" -d '{
  "message": {
    "topic" : "foo-bar",
    "notification": {
      "body": "This is a Firebase Cloud Messaging Topic Message!",
      "title": "FCM Message"
    }
  }
}' https://fcm.googleapis.com/v1/projects/myproject-b5ae1/messages:send HTTP/1.1

Para enviar un mensaje a una combinación de temas, debes especificar una condición, es decir, una expresión booleana en la que se especifican los temas de destino. Por ejemplo, la siguiente condición enviará mensajes a los dispositivos suscritos a TopicA, y a TopicB o TopicC:

"'TopicA' in topics && ('TopicB' in topics || 'TopicC' in topics)"

En primer lugar, FCM evalúa las condiciones en paréntesis y, luego, evalúa la expresión de izquierda a derecha. En la expresión anterior, un usuario suscrito a uno solo de los temas no recibirá el mensaje. Asimismo, un usuario que no está suscrito a TopicA no recibirá el mensaje. Las siguientes combinaciones sí lo reciben:

  • TopicA y TopicB
  • TopicA y TopicC

Puedes incluir hasta cinco temas en tu expresión condicional.

Para enviar mensajes a una condición, haz lo siguiente:

Node.js

// Define a condition which will send to devices which are subscribed
// to either the Google stock or the tech industry topics.
const condition = '\'stock-GOOG\' in topics || \'industry-tech\' in topics';

// See documentation on defining a message payload.
const message = {
  notification: {
    title: '$FooCorp up 1.43% on the day',
    body: '$FooCorp gained 11.80 points to close at 835.67, up 1.43% on the day.'
  },
  condition: condition
};

// Send a message to devices subscribed to the combination of topics
// specified by the provided condition.
getMessaging().send(message)
  .then((response) => {
    // Response is a message ID string.
    console.log('Successfully sent message:', response);
  })
  .catch((error) => {
    console.log('Error sending message:', error);
  });

Java

// Define a condition which will send to devices which are subscribed
// to either the Google stock or the tech industry topics.
String condition = "'stock-GOOG' in topics || 'industry-tech' in topics";

// See documentation on defining a message payload.
Message message = Message.builder()
    .setNotification(Notification.builder()
        .setTitle("$GOOG up 1.43% on the day")
        .setBody("$GOOG gained 11.80 points to close at 835.67, up 1.43% on the day.")
        .build())
    .setCondition(condition)
    .build();

// Send a message to devices subscribed to the combination of topics
// specified by the provided condition.
String response = FirebaseMessaging.getInstance().send(message);
// Response is a message ID string.
System.out.println("Successfully sent message: " + response);

Python

# Define a condition which will send to devices which are subscribed
# to either the Google stock or the tech industry topics.
condition = "'stock-GOOG' in topics || 'industry-tech' in topics"

# See documentation on defining a message payload.
message = messaging.Message(
    notification=messaging.Notification(
        title='$GOOG up 1.43% on the day',
        body='$GOOG gained 11.80 points to close at 835.67, up 1.43% on the day.',
    ),
    condition=condition,
)

# Send a message to devices subscribed to the combination of topics
# specified by the provided condition.
response = messaging.send(message)
# Response is a message ID string.
print('Successfully sent message:', response)

Go

// Define a condition which will send to devices which are subscribed
// to either the Google stock or the tech industry topics.
condition := "'stock-GOOG' in topics || 'industry-tech' in topics"

// See documentation on defining a message payload.
message := &messaging.Message{
	Data: map[string]string{
		"score": "850",
		"time":  "2:45",
	},
	Condition: condition,
}

// Send a message to devices subscribed to the combination of topics
// specified by the provided condition.
response, err := client.Send(ctx, message)
if err != nil {
	log.Fatalln(err)
}
// Response is a message ID string.
fmt.Println("Successfully sent message:", response)

C#

// Define a condition which will send to devices which are subscribed
// to either the Google stock or the tech industry topics.
var condition = "'stock-GOOG' in topics || 'industry-tech' in topics";

// See documentation on defining a message payload.
var message = new Message()
{
    Notification = new Notification()
    {
        Title = "$GOOG up 1.43% on the day",
        Body = "$GOOG gained 11.80 points to close at 835.67, up 1.43% on the day.",
    },
    Condition = condition,
};

// Send a message to devices subscribed to the combination of topics
// specified by the provided condition.
string response = await FirebaseMessaging.DefaultInstance.SendAsync(message);
// Response is a message ID string.
Console.WriteLine("Successfully sent message: " + response);

REST

POST https://fcm.googleapis.com/v1/projects/myproject-b5ae1/messages:send HTTP/1.1

Content-Type: application/json
Authorization: Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA
{
   "message":{
    "condition": "'dogs' in topics || 'cats' in topics",
    "notification" : {
      "body" : "This is a Firebase Cloud Messaging Topic Message!",
      "title" : "FCM Message",
    }
  }
}

Comando de cURL:

curl -X POST -H "Authorization: Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA" -H "Content-Type: application/json" -d '{
  "notification": {
    "title": "FCM Message",
    "body": "This is a Firebase Cloud Messaging Topic Message!",
  },
  "condition": "'dogs' in topics || 'cats' in topics"
}' https://fcm.googleapis.com/v1/projects/myproject-b5ae1/messages:send HTTP/1.1

Próximos pasos