react-native-push-notification / ios

React Native Push Notification API for iOS.
MIT License
734 stars 282 forks source link

Data is empty when app is on foreground #341

Closed anija closed 2 years ago

anija commented 2 years ago

I've tried a lot of solutions I've found on this repository, but nothing seems to works.

I've a remote notification with the data object filled up with some data. If the app is on background, i can get the full data object:

PushNotificationIOS.addEventListener('notification', (notification) => {
  console.log(notification.getData());
});

Console result:

{
  actionIdentifier: "com.apple.UNNotificationDefaultActionIdentifier"
  "gcm.message_id": "1633961938049579"
​  "google.c.a.e": "1"
​  "google.c.fid": "dzmv0-mDvUQyrfTFX0QyBz"
​  "google.c.sender.id": "147810287311"
​  link: "some link"
​  notificationUID: "8366038066243~IniiklJFrNfMdSwudWTG"
​  userInteraction: 1
​}

But when the app is on foreground, the notification is redirected as a local notification and is missing the data info:

PushNotificationIOS.addEventListener('notification', (notification) => {
  console.log(notification.getData())
});

Console result:

{
  actionIdentifier: "com.apple.UNNotificationDefaultActionIdentifier"
  ​userInteraction: 1
}

I think that the problem is in file AppDelegate.m, here:

//Called when a notification is delivered to a foreground app.
-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler
{
  // Still call the JS onNotification handler so it can display the new message right away
  NSDictionary *userInfo = notification.request.content.userInfo;
  NSLog(@"userInfo: %@", userInfo);
  completionHandler(UNNotificationPresentationOptionSound | UNNotificationPresentationOptionAlert | UNNotificationPresentationOptionBadge);
}

I got two different logs of userInfo: first time is complete, second time is empty.

Can someone help me on this? Thank you so much :)

anija commented 2 years ago

The problem was in another place at all.

messaging().onMessage(async remoteMessage => {
      PushNotification.localNotification({
        title: remoteMessage.notification?.title,
        message: remoteMessage.notification?.body||'',
        userInfo: remoteMessage.data,
      });
    });

I was missing userInfo here.