我正在将 Firebase Cloud Messaging 集成到 React Native 应用程序中,并且在 iOS 上遇到了一个小问题:如果应用程序在后台,通知会按预期显示,但如果应用程序在前台,则什么也不会发生。
我已经从 RNFirebase 文档中添加了 AppDelegate.m 代码,包括我理解的 iOS 10 新增的 withCompletionHandler 变体:
// From https://rnfirebase.io/docs/v3.3.x/messaging/ios:
-(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
[RNFirebaseMessaging didReceiveLocalNotification:notification];
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(nonnull NSDictionary *)userInfo {
[RNFirebaseMessaging didReceiveRemoteNotification:userInfo];
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(nonnull NSDictionary *)userInfo
fetchCompletionHandler:(nonnull void (^)(UIBackgroundFetchResult))completionHandler{
[RNFirebaseMessaging didReceiveRemoteNotification:userInfo fetchCompletionHandler:completionHandler];
}
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
willPresentNotification:(UNNotification *)notification
withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler {
[RNFirebaseMessaging willPresentNotification:notification withCompletionHandler:completionHandler];
}
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
didReceiveNotificationResponse:(UNNotificationResponse *)response
withCompletionHandler:(void (^)(void))completionHandler {
[RNFirebaseMessaging didReceiveNotificationResponse:response withCompletionHandler:completionHandler];
在 react-native 应用程序中,我有一个 onMessage 处理程序,它的工作方式与 iOS 模拟器和 Android 中宣传的一样:
// ...Initializing Firebase...
messaging.onMessage(handleMessage);
// Handle a message:
function handleMessage(message) {
console.log('Firebase: Received message:', message);
const theActualMessage = message.fcm ? message.fcm : message.notification;
if (typeof message.finish === 'function') {
message.finish();
}
Alert.alert('Push message', theActualMessage.body);
}
无论我是从 Firebase 控制台还是通过 HTTP API 发送推送通知,如果应用程序在后台,通知只会出现在 iOS(在真实设备上);我的handleMessage()
函数永远不会被调用。
在 iOS 模拟器、Android 模拟器和 Android 手机上,我的处理程序按预期调用——只有真正的 iOS 设备行为异常。