React-Native Firebase Push-уведомление onClick на определенную страницу в моем приложении - PullRequest
1 голос
/ 20 июня 2019

Я хочу сделать свое push-уведомление, чтобы после нажатия на него можно было перейти на определенную страницу «Отпечаток пальца». На данный момент push-уведомление ничего не делает при нажатии, кроме открытия приложения, если оно находится в фоновом режиме. Я искал в Интернете, проб и ошибок в течение двух дней безрезультатно. Любая помощь будет оценена.

import React, {Component} from 'react';
    import {Platform, StyleSheet, Text, View, Alert, AsyncStorage, Button} from 'react-native';
    import firebase from 'react-native-firebase';





type Props = {};
export default class testapp extends Component<Props> {


  async componentDidMount() {
    this.checkPermission();
    this.createNotificationListeners(); //add this line
  }

  componentWillUnmount() {
    this.notificationListener;
    this.notificationOpenedListener;
  }

  //1
  async checkPermission() {
    const enabled = await firebase.messaging().hasPermission();
    if (enabled) {
      this.getToken();
    } else {
      this.requestPermission();
    }
  }

  //3
  async getToken() {
    let fcmToken = await AsyncStorage.getItem('fcmToken');
    if (!fcmToken) {
      fcmToken = await firebase.messaging().getToken();
      if (fcmToken) {
        // user has a device token
        console.log('fcmToken:', fcmToken);
        await AsyncStorage.setItem('fcmToken', fcmToken);
      }
    }
    console.log('fcmToken:', fcmToken);
  }

  //2
  async requestPermission() {
    try {
      await firebase.messaging().requestPermission();
      // User has authorised
      this.getToken();
    } catch (error) {
      // User has rejected permissions
      console.log('permission rejected');
    }
  }

  async createNotificationListeners() {
    /*
    * Triggered when a particular notification has been received in foreground
    * */
    this.notificationListener = firebase.notifications().onNotification((notification) => {
      const { title, body } = notification;
      console.log('onNotification:');

        const localNotification = new firebase.notifications.Notification({
          sound: 'sampleaudio',
          show_in_foreground: true,
        })
        .setSound('sampleaudio.wav')
        .setNotificationId(notification.notificationId)
        .setTitle(notification.title)
        .setBody(notification.body)
        .android.setChannelId('fcm_FirebaseNotifiction_default_channel') // e.g. the id you chose above
        .android.setSmallIcon('@drawable/ic_launcher') // create this icon in Android Studio
        .android.setColor('#000000') // you can set a color here    
        // .setClickAction(()=>alert('test'))   
        .android.setPriority(firebase.notifications.Android.Priority.High);


        firebase.notifications()
          .displayNotification(localNotification)
          .catch(err => console.error(err));
    });

    const channel = new firebase.notifications.Android.Channel('fcm_FirebaseNotifiction_default_channel', 'UniFinalApp', firebase.notifications.Android.Importance.High)
      .setDescription('Demo app description')
      .setSound('sampleaudio.wav');
    firebase.notifications().android.createChannel(channel);

    /*
    Code would probably go in the section below
    * If your app is in background, you can listen for when a notification is clicked / tapped / opened as follows:
    * */
    this.notificationOpenedListener = firebase.notifications().onNotificationOpened((notificationOpen) => {
      const { title, body } = notificationOpen.notification;
      console.log('onNotificationOpened:');

      // Alert.alert(title, body)


    });

    /*
    * If your app is closed, you can check if it was opened by a notification being clicked / tapped / opened as follows:
    * */
    const notificationOpen = await firebase.notifications().getInitialNotification();
    if (notificationOpen) {
      const { title, body } = notificationOpen.notification;
      console.log('getInitialNotification:');
      Alert.alert(title, body)
    }
    /*
    * Triggered for data only payload in foreground
    * */
   this.messageListener = firebase.messaging().onMessage((message) => {
    //process data message
    console.log("JSON.stringify:", JSON.stringify(message));
  });
}
render() {
  // const {navigate}=this.props.navigation;
    return (
      <View >


      </View>
    );
  }
}

1 Ответ

0 голосов
/ 21 июня 2019

Внутри документации для React-native-firebase ; есть раздел о том, как обрабатывать данные из уведомлений. Что вы можете сделать, это отправить данные внутри уведомления, которое сообщит приложению, что делать. Например:

firebase.notifications().getInitialNotification()
.then((notificationOpen: NotificationOpen) => {
   if (notificationOpen) {
      // App was opened by a notification
      const notification: Notification = notificationOpen.notification;  
      const data = notificationOpen.notification._data;
        if (data.action === 'openChat') {
          //Code to open Chat screen  
        }
   }
});

Или вы можете использовать данные из уведомления, чтобы установить некоторые флаги, а затем, как только пользователь войдет в определенный экран (например, после входа в систему), проверяет флаги, чтобы увидеть, нужно ли выполнить определенное действие.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...