我使用的是最新的React Native版本0.62和最新版本的react-native-firebase,即v6。我能够收到通知,并且它可以在后台正常运行,但不会在前景上显示。
这是我的代码:
checkPermission = async () => {
const enabled = await messaging().hasPermission();
console.log('enabled ******* ',enabled)
if (enabled) {
this.getFcmToken();
} else {
this.requestPermission();
}
};
getFcmToken = async () => {
const fcmToken = await messaging().getToken();
if (fcmToken) {
console.log('Your Firebase Token is:', fcmToken);
// this.showAlert('Your Firebase Token is:', fcmToken);
} else {
console.log('Failed', 'No token received');
}
};
requestPermission = async () => {
try {
await messaging().requestPermission();
// User has authorised
} catch (error) {
// User has rejected permissions
}
};
messageListener = async () => {
console.log('inside message listener ****** ')
messaging().onMessage(async remoteMessage => {
Alert.alert('A new FCM message arrived!', JSON.stringify(remoteMessage));
};
showAlert = (title, message) => {
Alert.alert(
title,
message,
[{ text: 'OK', onPress: () => console.log('OK Pressed') }],
{ cancelable: false },
);
};
componentDidMount() {
this.checkPermission();
this.messageListener();
}
答案 0 :(得分:7)
默认情况下,rnfirebase 不支持在应用程序处于前台状态时显示通知弹出窗口,正如他们提到的 here。因此推送通知仅在应用处于后台状态或关闭时显示。
因此,如果您还想在前台模式下显示推送通知,那么您必须使用额外的库,该库将在他们的文档中提到将触发的推送通知显示为本地通知。
<块引用>如果 RemoteMessage 负载在发送到 onMessage 处理程序时包含通知属性,则设备将不会向用户显示任何通知。相反,您可以触发本地通知或更新应用内 UI 以发出新通知。
因此,作为一种解决方案,您可以使用 react-native-push-notification 在应用程序处于前台时触发推送通知。
为此,只需通过命令安装它:
<块引用>npm i react-native-push-notification
对于android,您不需要遵循任何本机安装步骤,只需通过此命令安装库,然后您就可以触发本地推送通知,如下所示: 创建一个名为 NotificationController.android.js 的文件:
import React, { useEffect } from 'react';
import { Alert } from 'react-native';
import messaging from '@react-native-firebase/messaging';
import PushNotification from 'react-native-push-notification';
const NotificationController = (props) => {
useEffect(() => {
const unsubscribe = messaging().onMessage(async (remoteMessage) => {
PushNotification.localNotification({
message: remoteMessage.notification.body,
title: remoteMessage.notification.title,
bigPictureUrl: remoteMessage.notification.android.imageUrl,
smallIcon: remoteMessage.notification.android.imageUrl,
});
});
return unsubscribe;
}, []);
return null;
};
export default NotificationController;
现在,当应用处于前台状态时,如果 onMessage
收到来自 firebase 的任何消息,则 PushNotification
将触发本地通知。
更新:适用于 iOS
对于 iOS,您必须使用以下命令安装 @react-native-community/push-notification-ios
:
npm i @react-native-community/push-notification-ios
同时按照文档中建议的所有本机安装步骤进行操作。
然后您可以创建名为 NotificationController.ios.js 的文件,您可以在其中处理 iOS 通知。
import { useEffect } from 'react';
import { Alert } from 'react-native';
import messaging from '@react-native-firebase/messaging';
import PushNotification from 'react-native-push-notification';
import PushNotificationIos from '@react-native-community/push-notification-ios';
const NotificationController = (props) => {
const navigation = useNavigation();
// Called when application is open by clicking on notification
// and called when application is already opend and user click on notification
PushNotification.configure({
onNotification: (notification) => {
if (notification) {
console.log(notification);
Alert.alert('Opened push notification', JSON.stringify(notification));
}
},
});
useEffect(() => {
// Usesd to display notification when app is in foreground
const unsubscribe = messaging().onMessage(async (remoteMessage) => {
PushNotificationIos.addNotificationRequest({
id: remoteMessage.messageId,
body: remoteMessage.notification.body,
title: remoteMessage.notification.title,
userInfo: remoteMessage.data,
});
});
return unsubscribe;
}, []);
return null;
};
export default NotificationController;
现在,在主屏幕或应用初始路由文件中调用 <NotificationController />
。
答案 1 :(得分:0)
在@Kishan Bharda 解决方案之后,我不得不为 IOS 前台通知做一些不同的事情(在这里,我在 index.js 中有代码而不是不同的文件):
import { AppRegistry, Platform } from 'react-native';
import App from './App';
import { name as appName } from './app.json';
import PushNotificationIOS from "@react-native-community/push-notification-ios";
import PushNotification from "react-native-push-notification";
if (Platform.OS === 'ios') {
// Must be outside of any component LifeCycle (such as `componentDidMount`).
PushNotification.configure({
onNotification: function (notification) {
console.log("NOTIFICATION:", notification);
const { foreground, userInteraction, title, message } = notification;
if (foreground && (title || message) && !userInteraction) PushNotification.localNotification(notification);
notification.finish(PushNotificationIOS.FetchResult.NoData);
}
});
}
AppRegistry.registerComponent(appName, () => App);
答案 2 :(得分:-1)
添加函数messageListener的行
const localNotif = new firebase.notifications.Notification()
.setTitle('Gazelkin')
.setBody(message.data.message)
.setSound('default')
firebase.notifications().displayNotification(localNotif).catch(err => console.error(err))