React-native-firebase: уведомления Pu sh не всегда работают на iOS - PullRequest
1 голос
/ 12 марта 2020

Я реализовал приложение на реагирующем языке, которое отправляет уведомления pu sh через Firebase. В большинстве случаев он работает хорошо, но иногда уведомления pu sh не принимаются устройством (в основном iOS 13 устройств).

Для устройств, получающих мои уведомления pu sh правильно, onNotification запускается каждый раз (передний план и фон).

Для устройств, не получающих мои уведомления pu sh, onMessage запускается (только на переднем плане).

пакет. json

"react-native-firebase": "^5.6.0"

Podfile

pod 'Firebase/Core', '~> 6.19.0'
pod 'Firebase/Functions', '~> 6.19.0'
pod 'Firebase/Messaging', '~> 6.19.0'
pod 'Firebase/Auth', '~> 6.19.0'

Чтобы проверить мои уведомления pu sh, я отправляю его через POSTMAN, используя API Firebase, с текущим Полезная нагрузка:

{
"to" : "my_FCM_token",
"priority" : "high",
"notification" : {
    "body" : "Body TEST",
    "title": "TEST Notification",
    "vibrate": 1,
    "sound": 1
},
"data" : {
    "key" : "value"
}
}

Обратите внимание, что это всегда возвращает мне успех

AppDelegate.m

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // FIREBASE CONFIG
    [FIRApp configure];

    // SETTING ROOT VIEW CONTROLLER
    RCTBridge *bridge = [[RCTBridge alloc] initWithDelegate:self launchOptions:launchOptions];
    RCTRootView *rootView = [[RCTRootView alloc] initWithBridge:bridge
                                               moduleName:@"MyModule"
                                        initialProperties:nil];
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    UIViewController *rootViewController = [UIViewController new];
    rootViewController.view = rootView;
    self.window.rootViewController = rootViewController;
    [self.window makeKeyAndVisible];
    [RNSplashScreen show];
    return YES;
 }   

Приложение. js

async componentDidMount() {

  firebase.messaging().hasPermission().then(enabled => {
    if (enabled) {
      firebase.messaging().getToken().then(token => {
        global.token = token;
      })
    } else {
      firebase.messaging().requestPermission()
        .then(() => {
          alert("Permission Accepted", error)
        })
        .catch(error => {
          alert("Permission Denied", error)
        });
     }
  });

  this.initialNotificationListener = firebase.notifications().getInitialNotification().then((notificationOpen: NotificationOpen) => {
    alert("Getting initial Notification")
  });

  this.notificationOpenedListener = firebase.notifications().onNotificationOpened((notificationOpen: NotificationOpen) => {
    alert("onNotificationOpened triggered")
  });

  this.notificationListener = firebase.notifications().onNotification((notification: Notification) => {
    alert("onNotification triggered")
  });

  this.onMessageListener = firebase.messaging().onMessage(async (remoteMessage) => {
    alert("onMessage triggered")
  });
}

componentWillUnmount() {
  this.notificationOpenedListener();
  this.notificationDisplayedListener();
  this.notificationListener();
  this.initialNotificationListener();
  this.onMessageListener();
}

Любая помощь будет оценена, спасибо :)

1 Ответ

1 голос
/ 09 апреля 2020

Я наконец-то заставил его работать с новым исправлением, которое было опубликовано с response-native-firebase.

Ниже приведены шаги, которые необходимо выполнить:

1) Вы должны обновить этот продукт до версии native-firebase v6: https://rnfirebase.io/migrating-to-v6

2) В вашем пакете. json добавьте:

"@react-native-firebase/app": "6.4.0-rc4",
"@react-native-firebase/messaging": "6.4.0-rc4"

3) В вашем приложении. js, добавьте этих слушателей:

  // When a user tap on a push notification and the app is in background
  this.backgroundNotificationListener = messaging().onNotificationOpenedApp(async (remoteMessage) => {
     alert("Background Push Notification opened")
  });

  // When a user tap on a push notification and the app is CLOSED
  this.closedAppNotificationListener = messaging().getInitialNotification().then((remoteMessage) => {
    if (remoteMessage) {
      alert("App Closed Push Notification opened")
    }
  });

  // When a user receives a push notification and the app is in foreground
  this.onMessageListener = messaging().onMessage(() => {
     alert("Foreground Push Notification opened")
  });

Вы можете найти более подробную информацию о слушатели здесь: https://rnfb-docs.netlify.com/messaging/notifications#handling -взаимодействие

И вот обсуждение, которое решило мою проблему: https://github.com/invertase/react-native-firebase/pull/3339

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