使用Firebase云消息传递向React Native应用程序发送通知

使用Firebase云消息传递向React Native应用程序发送通知

响应本机云消息传递

这是我们的第八篇文章 反应原生 Firebase 系列,在这个例子中我们将看到什么是 Firebase Cloud Messaging? 消息类型,如何发送云消息? 如何在React Native应用程序中接收Firebase云消息? 让我们从 React Native 示例中的 Firebase 云消息传递开始。

推荐:如何在Windows 11使用照片应用程序背景模糊功能

Firebase 云消息传递

Firebase Cloud Messaging 是一款跨平台云解决方案,适用于 Android、iOS 和 Web 应用程序的消息和通知,并且免费提供。 使用 Firebase Cloud Messaging (FCM),我们可以轻松通知客户端应用程序有关新更新的信息,或者可以发送优惠或退出消息以保持他们的参与度。 FCM 是推动用户重新参与和保留的最佳方式。 我们还可以将 FCM 用于即时消息(聊天应用程序),因为消息可以将高达 4KB 的有效负载传输到客户端应用程序。

消息类型

使用 FCM,您可以向客户端发送两种类型的消息:

  • 通知消息,有时被认为是“显示消息”。 这些由 FCM SDK 自动处理
  • 数据信息,由客户端应用程序处理

通知消息包含一组预定义的用户可见键。 相比之下,数据消息仅包含用户定义的自定义键值对。

通知消息可以包含可选的数据负载,它也可以帮助您在通知消息中发送数据。 两种消息类型的最大负载均为 4KB,从 Firebase 控制台发送消息时除外,该控制台强制执行 1024 个字符的限制。

你可以看到 关于 FCM 消息 了解有关通知类型的更多信息。

示例说明

在此示例中,我们将在 React Native 应用程序中设置 Firebase Cloud Messaging 环境,并从 Firebase 控制台发送通知。 从控制台发送 Firebase Cloud 消息不切实际,因此我们使用以下命令创建了一个节点服务器 Firebase 管理 SDK 这可以帮助我们发送通知。 让我们开始设置和代码。

制作 React Native 应用程序

React Native 入门将帮助您更多地了解如何制作 React Native 项目。 我们将使用 React Native 命令行界面来制作我们的 React Native 应用程序。

如果您之前安装了全局的react-native-cli软件包,请将其删除,因为它可能会导致意外问题:

npm uninstall -g react-native-cli @react-native-community/cli

运行以下命令创建一个新的 React Native 项目

npx react-native init ProjectName

如果你想使用特定的 React Native 版本启动一个新项目,你可以使用 –version 参数:

npx react-native init ProjectName --version X.XX.X

注意如果上述命令失败,您可能使用的是旧版本 react-native 或者 react-native-cli 在您的电脑上全局安装。 尝试卸载 cli 并使用 npx 运行 cli。

这将在项目目录中创建一个带有名为 App.js 的索引文件的项目结构。

Firebase SDK 集成

要从任何 React Native Firebase 示例开始,您需要将 Firebase 集成到您的应用程序中,我专门为此详细制作了一篇单独的文章,您将在其中看到在 Android 版 React Native 应用程序中添加 Firebase 的点对点过程,以及iOS 两者都有。

请访问如何在 Android 和 iOS 应用程序中集成 Firebase,然后返回执行下一步。

完成 Firebase 集成后,您可以安装更多依赖项。

安装依赖项

要安装依赖项,请打开终端并使用以下命令跳转到您的项目

cd ProjectName

对于 React Native Firebase,我们需要安装和设置应用程序模块

npm install @react-native-firebase/app --save

现在安装消息模块

npm install  @react-native-firebase/messaging --save

此命令会将所有依赖项复制到您的 node_module 目录中。 –save 是可选的,它只是更新 package.json 文件中的依赖项。

CocoaPods 安装

React Native 0.60 更新后,他们引入了自动链接,因此我们不需要链接库,但对于 iOS,我们需要安装 pod。 因此要安装 pod,请使用

cd ios/ && pod install --repo-update && cd ..

React Native Firebase 云消息传递代码

请在任何代码编辑器中打开 App.js 并将代码替换为以下代码

应用程序.js

/*
 * #8 Send Notification to React Native App using
 * Firebase Cloud Messaging
 * https://aboutreact.com/react-native-notification-firebase-cloud-messaging
 */

// import React in our code
import React, {useEffect} from 'react';

// import all the components we are going to use
import {
  SafeAreaView,
  StyleSheet,
  View,
  Text,
  Image
} from 'react-native';

import messaging from '@react-native-firebase/messaging';

const TOPIC = 'MyNews';

const App = () => {
  const requestUserPermission = async () => {
    /**
     * On iOS, messaging permission must be requested by
     * the current application before messages can be
     * received or sent
     */
    const authStatus = await messaging().requestPermission();
    console.log('Authorization status(authStatus):', authStatus);
    return (
      authStatus === messaging.AuthorizationStatus.AUTHORIZED ||
      authStatus === messaging.AuthorizationStatus.PROVISIONAL
    );
  };

  useEffect(() => {
    if (requestUserPermission()) {
      /**
       * Returns an FCM token for this device
       */
      messaging()
        .getToken()
        .then((fcmToken) => {
          console.log('FCM Token -> ', fcmToken);
        });
    } else console.log('Not Authorization status:', authStatus);

    /**
     * When a notification from FCM has triggered the application
     * to open from a quit state, this method will return a
     * `RemoteMessage` containing the notification data, or
     * `null` if the app was opened via another method.
     */
    messaging()
      .getInitialNotification()
      .then(async (remoteMessage) => {
        if (remoteMessage) {
          console.log(
            'getInitialNotification:' +
              'Notification caused app to open from quit state',
          );
          console.log(remoteMessage);
          alert(
            'getInitialNotification: Notification caused app to' +
            ' open from quit state',
          );
        }
      });

    /**
     * When the user presses a notification displayed via FCM,
     * this listener will be called if the app has opened from
     * a background state. See `getInitialNotification` to see
     * how to watch for when a notification opens the app from
     * a quit state.
     */
    messaging().onNotificationOpenedApp(async (remoteMessage) => {
      if (remoteMessage) {
        console.log(
          'onNotificationOpenedApp: ' +
            'Notification caused app to open from background state',
        );
        console.log(remoteMessage);
        alert(
          'onNotificationOpenedApp: Notification caused app to' +
          ' open from background state',
        );
      }
    });

    /**
     * Set a message handler function which is called when
     * the app is in the background or terminated. In Android,
     * a headless task is created, allowing you to access the
     * React Native environment to perform tasks such as updating
     * local storage, or sending a network request.
     */
    messaging().setBackgroundMessageHandler(
      async (remoteMessage) => {
        console.log(
          'Message handled in the background!',
          remoteMessage
        );
    });

    /**
     * When any FCM payload is received, the listener callback
     * is called with a `RemoteMessage`. Returns an unsubscribe
     * function to stop listening for new messages.
     */
    const unsubscribe = messaging().onMessage(
      async (remoteMessage) => {
        alert('A new FCM message arrived!');
        console.log(
          'A new FCM message arrived!',
          JSON.stringify(remoteMessage)
        );
      }
    );

    /**
     * Apps can subscribe to a topic, which allows the FCM
     * server to send targeted messages to only those devices
     * subscribed to that topic.
     */
    messaging()
      .subscribeToTopic(TOPIC)
      .then(() => {
        console.log(`Topic: ${TOPIC} Suscribed`);
      });

    return () => {
      unsubscribe;
      /**
       * Unsubscribe the device from a topic.
       */
      // messaging().unsubscribeFromTopic(TOPIC);
    };
  }, ());

  return (
    <SafeAreaView style={styles.container}>
      <View style={styles.container}>
        <Text style={styles.titleText}>
          Send Notification to React Native App
        </Text>
        <Text style={styles.textStyle}>using</Text>
        <Image
          source={require('./Image/firebase.png')}
          style={{
            width: '90%',
            height: '50%',
            resizeMode: 'contain',
            margin: 30,
          }}
        />
        <Text style={styles.titleText}>
          Firebase Cloud Messaging
        </Text>
      </View>
      <Text
        style={{
          fontSize: 16,
          textAlign: 'center',
          color: 'white',
        }}>
        www.aboutreact.com
      </Text>
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 16,
    textAlign: 'center',
    backgroundColor: '#307ecc',
  },
  titleText: {
    fontSize: 24,
    textAlign: 'center',
    fontWeight: 'bold',
    marginVertical: 10,
    color: 'white',
  },
  textStyle: {
    fontSize: 20,
    fontWeight: 'bold',
    textAlign: 'center',
    marginBottom: 10,
    color: 'white',
  },
});

export default App;

从 Firebase 控制台发送云消息

从 Firebase 控制台发送 Firebase Cloud 消息 打开 Firebase 控制台,选择项目并从左侧菜单中选择云消息传递。

React_native_cloud_message_send_notification1

单击“发送您的第一条消息”,您将看到用于撰写通知的输入/选项。 您可以插入通知的标题、文本和图像。

React_native_cloud_message_send_notification2

单击“下一步”后,您将看到用于选择目标受众的选项。 您可以选择一个 用户细分 或一个 话题。 有很多选项可以选择您的受众 用户细分 选项本身就像您可以根据应用程序版本、语言、国家/地区、用户受众等发送消息。

React_native_cloud_message_send_notification3

您可以立即发送,也可以安排稍后发送消息

React_native_cloud_message_send_notification4

查看消息和 发布

React_native_cloud_message_send_notification5

输出截图

React_native_cloud_message_send_notification12

用于发送 Firebase 云消息的节点服务器

您可以从控制台发送云消息,但实际上您需要一种方法来从服务器触发云消息。 Firebase 管理 SDK 会帮助你做到这一点。 这是使用 Firebase Admin SDK 创建的 Node.js 小项目。

在运行此项目之前,您必须获取 service-account.json 文件以将服务器与 Firebase 实例连接。 要获取 service-account.json 文件,请打开控制台,单击设置图标并选择“项目设置”,打开项目设置后,单击“服务帐户”选项卡,您将看到生成新私钥的选项。 该密钥与我们连接 Firebase 实例所需的文件相同。

React_native_cloud_message_send_notification13

下载的服务帐户文件可以有一个长名称,扩展名为 json,您可以根据需要重命名它。 现在您可以使用以下步骤设置节点服务器。

1. 克隆仓库

git clone https://github.com/SnehalAgrawal/about-react-dummy-firebase-apis.git

2. 跳转到目录

cd about-react-dummy-firebase-apis

3.安装node_module

npm install

4.更新服务帐户文件路径

const serviceAccount =
require("/Users/kepi/Desktop/MainRepo/service-account-file.json");

5. 运行服务器

npm start

这将为您启动您的服务器

React_native_cloud_message_server

服务器启动并运行后,您可以使用以下 URL 发送通知

http://localhost:3000/notify/

这是您在适用于 Android 和 iOS 的 React Native 应用程序中发送 Firebase 云消息的方法。 如果您有任何疑问或想分享有关该主题的内容,您可以在下面发表评论或在此处联系我们

推荐:在Amazon Linux 2023上安装MySQL 8服务器客户端


发表评论