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

RN Firebase推送通知在iOS模拟器接收消息但不显示问题

React Native Firebase 推送通知:模拟器能接收消息但不显示通知

我基于React Native Firebase开发推送通知功能,已按照官方文档完成配置,能在console.log中获取到远程消息,但Xcode模拟器上无法显示通知。以下是相关代码与配置截图:

1. notificationservices.js 代码

import messaging from "@react-native-firebase/messaging";
import PushNotification from "react-native-push-notification";
import {PushNotificationIOS} from "@react-native-community/push-notification-ios";
import {Platform} from "react-native";

const getFcmToken = async () => {
    const fcmToken = await messaging()
        .registerDeviceForRemoteMessages()
        .then(() => messaging().getToken());
    console.log("fcmToken ==>", fcmToken);

    if (fcmToken) {
        console.log("Your Firebase Token is:", fcmToken);
    } else {
        console.log("Failed", "No token received");
    }
};

export const requestUserPermission = async () => {
    const authStatus = await messaging().requestPermission();
    const enabled =
        authStatus === messaging.AuthorizationStatus.AUTHORIZED ||
        authStatus === messaging.AuthorizationStatus.PROVISIONAL;

    if (enabled) {
        getFcmToken();
        console.log("Authorization status:", authStatus);
    }
};

export const notficationListener = async () => {
    messaging().onNotificationOpenedApp(remoteMessage => {
        console.log(
            "Notification caused app to open from background state:",
            remoteMessage.notification,
        );
    });
    messaging()
        .getInitialNotification()
        .then(remoteMessage => {
            if (remoteMessage) {
                console.log(
                    "Notification caused app to open from quit state:",
                    remoteMessage.notification,
                );
            }
        });
    messaging().onMessage(async remotemessage => {
        console.log("remote message11", JSON.stringify(remotemessage));
    });
    messaging().onNotificationOpenedApp(remotemessage => {
        console.log("remote message11", JSON.stringify(remotemessage));
        PushNotificationIOS.addNotificationRequest({
            id: remotemessage.messageId,
            title: remotemessage.notification.title,
            body: remotemessage.notification.body,
            sound: "default",
        });

        PushNotification.configure({
            onNotification: function (notification) {
                console.log("push notification");
                if (!notification.data) {
                    return;
                }
                notification.userInteraction = true;
                if (Platform.OS === "ios") {
                    notification.finish(PushNotificationIOS.FetchResult.NoData);
                }
            },
            senderId: "1054317504462",
            permissions: {
                alert: true,
                badge: true,
                sound: true,
            },
            popInitialNotification: true,
            requestPermissions: true,
        });
    });
};

export const remoteMessage = () => {
    const unsubscribe = messaging().onMessage(async remoteMessage1 => {
        console.log("A new FCM message arrived!", JSON.stringify(remoteMessage1));
    });
    return unsubscribe;
};

2. Xcode 签名与证书配置

签名与证书截图

3. AppDelegate.m 代码

#import "AppDelegate.h"

#import <Firebase.h>
#import <React/RCTBridge.h>
#import <React/RCTBundleURLProvider.h>
#import <React/RCTRootView.h>
#import "RNNotifications.h"

#ifdef FB_SONARKIT_ENABLED
#import <FlipperKit/FlipperClient.h>
#import <FlipperKitLayoutPlugin/FlipperKitLayoutPlugin.h>
#import <FlipperKitUserDefaultsPlugin/FKUserDefaultsPlugin.h>
#import <FlipperKitNetworkPlugin/FlipperKitNetworkPlugin.h>
#import <SKIOSNetworkPlugin/SKIOSNetworkAdapter.h>
#import <FlipperKitReactPlugin/FlipperKitReactPlugin.h>

static void InitializeFlipper(UIApplication *application) {
  FlipperClient *client = [FlipperClient sharedClient];
  SKDescriptorMapper *layoutDescriptorMapper = [[SKDescriptorMapper alloc] initWithDefaults];
  [client addPlugin:[[FlipperKitLayoutPlugin alloc] initWithRootNode:application withDescriptorMapper:layoutDescriptorMapper]];
  [client addPlugin:[[FKUserDefaultsPlugin alloc] initWithSuiteName:nil]];
  [client addPlugin:[FlipperKitReactPlugin new]];
  [client addPlugin:[[FlipperKitNetworkPlugin alloc] initWithNetworkAdapter:[SKIOSNetworkAdapter new]]];
  [client start];
}
#endif

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
 [FIRApp configure];
#ifdef FB_SONARKIT_ENABLED
  InitializeFlipper(application);
#endif

  RCTBridge *bridge = [[RCTBridge alloc] initWithDelegate:self launchOptions:launchOptions];
  RCTRootView *rootView = [[RCTRootView alloc] initWithBridge:bridge
                                                   moduleName:@"AirU_App"
                                            initialProperties:nil];

  if (@available(iOS 13.0, *)) {
      rootView.backgroundColor = [UIColor systemBackgroundColor];
  } else {
      rootView.backgroundColor = [UIColor whiteColor];
  }

  self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
  UIViewController *rootViewController = [UIViewController new];
  rootViewController.view = rootView;
  self.window.rootViewController = rootViewController;
  [self.window makeKeyAndVisible];
  return YES;
}

问题排查与解决方案

1. iOS 模拟器通知显示限制

  • 确保使用**iOS 13+**版本的模拟器,旧版本对推送通知支持不完善
  • 模拟器需登录Apple ID:打开模拟器设置 > Apple ID登录账号,未登录的模拟器无法接收推送通知

2. 前台通知显示缺失

iOS中App前台运行时,FCM不会自动弹出通知,需手动创建本地通知。修改notficationListener中的onMessage回调:

messaging().onMessage(async remotemessage => {
    console.log("remote message11", JSON.stringify(remotemessage));
    // 手动创建前台通知
    if (Platform.OS === 'ios') {
        PushNotificationIOS.addNotificationRequest({
            id: remotemessage.messageId,
            title: remotemessage.notification.title,
            body: remotemessage.notification.body,
            sound: 'default',
            userInfo: remotemessage.data
        });
    } else {
        PushNotification.localNotification({
            title: remotemessage.notification.title,
            message: remotemessage.notification.body,
            soundName: 'default',
            userInfo: remotemessage.data
        });
    }
});

3. AppDelegate 配置缺失

当前AppDelegate未实现APNs相关回调,需添加以下代码到AppDelegate.m:

// 处理后台推送通知
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
  [[RNFirebaseMessaging instance] didReceiveRemoteNotification:userInfo fetchCompletionHandler:completionHandler];
}

// 注册APNs成功后获取device token
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
  [[RNFirebaseMessaging instance] didRegisterForRemoteNotificationsWithDeviceToken:deviceToken];
}

// 注册APNs失败
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
  [[RNFirebaseMessaging instance] didFailToRegisterForRemoteNotificationsWithError:error];
}

4. PushNotification 配置时机错误

PushNotification.configure不应放在onNotificationOpenedApp回调中,需移到全局初始化位置,比如组件挂载时:

export const notficationListener = async () => {
    // 先初始化PushNotification配置
    PushNotification.configure({
        onNotification: function (notification) {
            console.log("push notification");
            if (!notification.data) {
                return;
            }
            notification.userInteraction = true;
            if (Platform.OS === "ios") {
                notification.finish(PushNotificationIOS.FetchResult.NoData);
            }
        },
        senderId: "1054317504462",
        permissions: {
            alert: true,
            badge: true,
            sound: true,
        },
        popInitialNotification: true,
        requestPermissions: true,
    });

    // 其他监听逻辑保持不变
    messaging().onNotificationOpenedApp(remoteMessage => {
        console.log(
            "Notification caused app to open from background state:",
            remoteMessage.notification,
        );
    });
    // ... 剩余监听代码
};

5. 检查推送消息格式

确保Firebase控制台发送的通知包含notification字段,纯data消息在iOS后台/前台都不会自动弹出通知,需客户端手动处理。


内容的提问来源于stack exchange,提问作者Abdur Rehman Khalid

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 10:13:04