React Native FCM iOS前台通知不显示问题求助
这是iOS系统的默认行为哦——和Android不同,iOS应用在前台运行时,系统不会自动弹出远程推送的通知横幅。不过别担心,我们可以通过几行代码手动配置,让前台也能正常显示通知。下面是具体的解决步骤:
1. 配置UNUserNotificationCenter代理(iOS 10+)
首先,我们需要利用iOS 10引入的UNUserNotificationCenter来控制前台通知的展示逻辑:
- 在
AppDelegate.m顶部导入UserNotifications框架:
#import <UserNotifications/UserNotifications.h>
- 让AppDelegate遵守
UNUserNotificationCenterDelegate协议,修改@interface行:
@interface AppDelegate : UIResponder <UIApplicationDelegate, RCTBridgeDelegate, UNUserNotificationCenterDelegate>
- 在
didFinishLaunchingWithOptions方法中设置代理:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // 保留你原有的初始化代码... // 配置UNUserNotificationCenter代理 if (@available(iOS 10.0, *)) { UNUserNotificationCenter *notificationCenter = [UNUserNotificationCenter currentNotificationCenter]; notificationCenter.delegate = self; } return YES; }
2. 实现前台通知展示逻辑
添加willPresentNotification代理方法,明确告诉系统在前台收到通知时要展示的内容类型(横幅、声音、角标):
// iOS 10+ 前台收到通知时的处理 - (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler { // 指定要展示的通知类型:alert(横幅)、sound(声音)、badge(角标) completionHandler(UNNotificationPresentationOptionAlert | UNNotificationPresentationOptionSound | UNNotificationPresentationOptionBadge); // 如需处理自定义数据,可在这里获取 NSDictionary *userInfo = notification.request.content.userInfo; NSLog(@"Foreground notification data: %@", userInfo); }
3. 确认推送Payload格式正确
确保你的FCM推送Payload包含aps.alert字段,示例格式如下:
{ "aps": { "alert": { "title": "通知标题", "body": "通知内容" }, "sound": "default", "badge": 1 }, "customData": "你的自定义业务数据" }
4. 验证通知权限
确保应用已经请求了包含alert权限的通知权限,在React Native端可以用react-native-fcm的requestPermissions方法:
import FCM from 'react-native-fcm'; FCM.requestPermissions({ badge: true, sound: true, alert: true });
完成以上配置后,当你的iOS应用在前台运行时,收到FCM推送就会自动弹出通知横幅了。同时你原来的didReceiveRemoteNotification方法和RN端的FCM.on()监听器依然可以正常获取通知数据,两者互不影响。
内容的提问来源于stack exchange,提问作者devedv
相关产品推荐
相关产品推荐

