React-Native - Firebase Cloud Messaging - нет событий, если открыт из трея - PullRequest
0 голосов
/ 19 мая 2018

Я использую fcm-package (https://github.com/evollu/react-native-fcm) для отправки Firebase-Cloud-Messages на android.

Сообщения приходят на телефон.

Если приложение находится в фоновом режиме,уведомление появляется в строке состояния. Если я нажимаю на сообщение, приложение открывается на главном экране - в моем случае это News_Screen.

НО Я не нашел способапоймать данные уведомлений, после того, как приложение выходит на передний план.

FCM.on(FCMEvent.Notification, (notif) => { не получает никаких событий.

Если приложение находится на переднем плане, и я отправляю уведомление, console.log -выходная работа.

Я что-то упускаю, чтобы иметь возможность получать данные о событиях, если приложение выходит из фона на передний план?

Это структура моего приложения:

index.js ⇒ /app/index.js ⇒ (imports a StackNavigator)

Экран по умолчанию для StackNavigator - "News_Screen".

В окне новостей у меня есть это:

async componentDidMount() {

        // START Firebase Cloud Messaging
        try {
            let result = await FCM.requestPermissions({
                badge: false,
                sound: true,
                alert: true
            });
        } catch (e) {
            console.error(e);
        }

        FCM.getFCMToken().then(token => {
            this.setState({token: token || ""});
            console.log("First the token: ", token)
            // store fcm token in your server
        });
        if (Platform.OS === "ios") {
            FCM.getAPNSToken().then(token => {
                console.log("APNS TOKEN (getFCMToken)", token);
            });
        }

FCM.on(FCMEvent.Notification, (notif) => {
            if(notif.opened_from_tray){
                setTimeout(()=>{
                    console.log("notif.opened_from_tray", notif);
                }, 1000)
            }

            // there are two parts of notif. notif.notification contains the notification payload, notif.data contains data payload
            console.log("Message erhalten", notif);
            if (notif.screen !== undefined) {
                console.log("Jo, der Screen is", notif.screen, this.props.navigation);
                this.props.navigation.navigate('Menu_Screen');
            }
        });
        FCM.on(FCMEvent.RefreshToken, (token) => {
            console.log("Again the token:", token)
            // fcm token may not be available on first load, catch it here
        });
    }

Единственный файл console.log, который я получил, если нажать на уведомление и приложение перешло из фона на передний план, - это сообщение First the token....

КакМогу ли я поймать данные уведомления.(Например, если в уведомлении есть дополнительный Object-Parmete: screen: 'Menu_Screen, чтобы переключиться на этот экран после того, как приложение выйдет на передний план)

1 Ответ

0 голосов
/ 19 мая 2018

измените ваш слушатель на что-то вроде этого.

FCM.on(FCMEvent.Notification, notif => {
      console.log("Notification", notif);

      if(Platform.OS ==='ios' && notif._notificationType === NotificationType.WillPresent && !notif.local_notification){
        notif.finish(WillPresentNotificationResult.All)
        return;
      }

      if(Platform.OS ==='ios'){
        switch(notif._notificationType){
          case NotificationType.Remote:
            notif.finish(RemoteNotificationResult.NewData)
            break;
          case NotificationType.NotificationResponse:
            notif.finish();
            break;
          case NotificationType.WillPresent:
            notif.finish(WillPresentNotificationResult.All)
            break;
        }
      }

      this.showLocalNotification(notif)
    });

showLocalNotification(notif) {
  console.log('here local', notif)
    FCM.presentLocalNotification({
      title: notif.title,
      body: notif.body,
      priority: "high",
      show_in_foreground: true,
      local: true
   });
}

если приложение находится на переднем плане, эта строка NotificationType.WillPresent будет перехватывать данные уведомления.

...