RNFirebase v6 Pu sh Уведомления не приходят ни iOS, ни Android - PullRequest
0 голосов
/ 04 марта 2020

Я пытаюсь отправлять уведомления из консоли Firebase в мое реактивное приложение

Я следовал здесь плохой документации, насколько я понимаю: https://invertase.io/oss/react-native-firebase/v6/messaging/quick-start

Я установил @ response-native-firebase / app и / messaging, и вот мой код в компоненте:

  componentDidMount() {

    this.reqNotifications()
    this.checkNotificationPermission()

  }


  reqNotifications() {

    requestNotifications(['alert', 'badge', 'sound']).then(({status, settings}) => {

      console.log('NOTIFICATION STATUS' + status)

    });

  }

  async checkNotificationPermission() {
    const enabled =  await messaging().hasPermission();
    if (enabled) {
      console.log('APPROVED');
      await messaging().registerForRemoteNotifications()
      messaging().getToken().then(token => console.log('token: >> ' + token))



    } else {
      console.log('NOT APPROVED');
    }
  }
  • Я запрашиваю разрешение с помощью response-native-permissions, и запрос на разрешение работает .
  • Мои APN Apple OK на консоли Apple и Firebase
  • И я получаю свой токен методом getToken () в коде успешно .

Но я не могу отправить что-либо на устройство из firebase; ничего не происходит ни на переднем плане, ни на заднем плане. Я попытался проверить с помощью токена, а также попробовал нормально, но нет, ничего не происходит.

Я добавил этот код в componentDidMount:

messaging().onMessage(async remoteMessage => {
  console.log('FCM Message Data:', remoteMessage.data);
});

Как я понимаю, подписка на облачные сообщения и при отправке некоторые уведомления о облачных сообщениях от firebase-console, я должен получить консольный вывод; но ничего не происходит.

Я не знаю, что мне не хватает, но я думаю, что в этом пакете есть большое обновление, и большинство документов для предыдущей версии, и я действительно застрял здесь, спасибо за помощь

1 Ответ

0 голосов
/ 20 апреля 2020
for rnfirebase.io V6
 componentDidMount = async () => {
    this.checkNotificationPermission();
    await messaging().requestPermission({provisional: true});
    await messaging().registerDeviceForRemoteMessages();

    await this.getFCMToken();
    if (Platform.OS === 'android') {
      this.createAndroidNotificationChannel();
    }

    this.backgroundState();
    this.foregroundState();
  };   
checkNotificationPermission = () => {
    firebase
      .messaging()
      .hasPermission()
      .then(enabled => {
        if (!enabled) {
          this.promptForNotificationPermission();
        }
      });
  };

  promptForNotificationPermission = () => {
    firebase
      .messaging()
      .requestPermission({provisional: true})
      .then(() => {
        console.log('Permission granted.');
      })
      .catch(() => {
        console.log('Permission rejected.');
      });
  };

  createAndroidNotificationChannel() {
    const channel = new firebase.notifications.Android.Channel(
      'channelId',
      'Push Notification',
      firebase.notifications.Android.Importance.Max,
    ).setDescription('Turn on to receive push notification');

    firebase.notifications().android.createChannel(channel);
  }
 foregroundState = () => {
    const unsubscribe = messaging().onMessage(async notification => {
      console.log('Message handled in the foregroundState!', notification);
    });

    return unsubscribe;
  };

  // Register background handler
  backgroundState = () => {
    messaging().setBackgroundMessageHandler(async notification => {
      console.log('Message handled in the background!', notification);
    });
  };
...