You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求可测试Firebase iOS通知的简易React Native现成源码(MacBook可构建)

简易React Native Firebase推送通知测试项目(iOS)

前置准备

  • 已安装Xcode、Node.js、React Native CLI
  • 已在Firebase控制台创建iOS项目,下载好GoogleService-Info.plist配置文件

项目搭建与配置

  1. 创建基础项目并进入目录:
npx react-native init PushTestApp
cd PushTestApp
  1. 安装Firebase核心与消息推送依赖:
npm install @react-native-firebase/app @react-native-firebase/messaging
  1. iOS端配置:
  • 打开Xcode,将GoogleService-Info.plist拖入项目的PushTestApp根目录,务必勾选"Copy items if needed"
  • 在Xcode项目设置的Signing & Capabilities标签页,添加Push Notifications能力;再添加Background Modes能力,勾选其中的Remote notifications选项

核心测试代码

替换项目根目录的App.js为以下代码:

import React, { useEffect, useState } from 'react';
import { View, Text, StyleSheet } from 'react-native';
import messaging from '@react-native-firebase/messaging';

const App = () => {
  const [fcmToken, setFcmToken] = useState('');
  const [receivedNotification, setReceivedNotification] = useState(null);

  // 请求用户通知权限
  const requestNotificationPermission = async () => {
    const authStatus = await messaging().requestPermission();
    const isEnabled =
      authStatus === messaging.AuthorizationStatus.AUTHORIZED ||
      authStatus === messaging.AuthorizationStatus.PROVISIONAL;

    if (isEnabled) getDeviceFcmToken();
  };

  // 获取设备FCM Token
  const getDeviceFcmToken = async () => {
    const token = await messaging().getToken();
    setFcmToken(token);
    console.log('当前设备FCM Token:', token);
  };

  // 监听前台推送通知
  useEffect(() => {
    const unsubscribe = messaging().onMessage(async remoteMsg => {
      setReceivedNotification(remoteMsg);
      console.log('前台收到推送:', remoteMsg);
    });
    return unsubscribe;
  }, []);

  // 监听后台/未启动状态下的通知点击
  useEffect(() => {
    // 后台状态点击通知唤醒应用
    const bgUnsubscribe = messaging().onNotificationOpenedApp(remoteMsg => {
      console.log('后台点击通知打开应用:', remoteMsg);
      setReceivedNotification(remoteMsg);
    });

    // 未启动状态点击通知唤醒应用
    messaging()
      .getInitialNotification()
      .then(remoteMsg => {
        if (remoteMsg) {
          console.log('未启动时点击通知打开应用:', remoteMsg);
          setReceivedNotification(remoteMsg);
        }
      });

    return bgUnsubscribe;
  }, []);

  useEffect(() => {
    requestNotificationPermission();
  }, []);

  return (
    <View style={styles.container}>
      <Text style={styles.title}>Firebase推送测试</Text>
      {fcmToken ? (
        <Text style={styles.tokenText}>FCM Token: {fcmToken}</Text>
      ) : (
        <Text style={styles.tokenText}>正在获取设备Token...</Text>
      )}
      {receivedNotification && (
        <View style={styles.notificationCard}>
          <Text style={styles.notificationTitle}>收到推送:</Text>
          <Text>标题: {receivedNotification.notification.title}</Text>
          <Text>内容: {receivedNotification.notification.body}</Text>
        </View>
      )}
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    padding: 20,
    backgroundColor: '#f5f5f5',
  },
  title: {
    fontSize: 22,
    fontWeight: '600',
    marginBottom: 25,
  },
  tokenText: {
    fontSize: 14,
    marginBottom: 25,
    textAlign: 'center',
    color: '#333',
  },
  notificationCard: {
    width: '100%',
    padding: 18,
    backgroundColor: '#fff',
    borderRadius: 10,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.15,
    shadowRadius: 4,
    elevation: 3,
  },
  notificationTitle: {
    fontWeight: '600',
    marginBottom: 8,
    fontSize: 16,
  },
});

export default App;

运行测试

在项目根目录执行命令启动iOS模拟器:

npx react-native run-ios

推送测试步骤

  1. 从Xcode控制台复制输出的FCM Token
  2. 打开Firebase控制台的Cloud Messaging模块,创建测试消息
  3. 在消息目标中选择"单个设备",粘贴复制的FCM Token,发送即可测试三种状态(前台、后台、应用未启动)下的推送通知

内容的提问来源于stack exchange,提问作者Chau Loi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 12:35:23