react-native-notifications icon indicating copy to clipboard operation
react-native-notifications copied to clipboard

Notification Event Callbacks are not Firing on iOS

Open ryanpatk opened this issue 6 years ago • 55 comments

Thanks for picking up the task of being the only free and maintained PN library for react-native 🙏

react-native: 61.0 react-native-notifications: 3.1.4

I have followed the installation instructions exactly as outlined, and have picked up a few additional snippets from other github issues that have helped me get to a perfectly functioning Android implementation for foreground, background (warm) and background (cold) notifications.

Im having some issues on iOS though, namely none of the native event callbacks are firing: registerNotificationOpened registerNotificationReceivedBackground registerNotificationReceivedForeground

I am receiving push notifications on iOS and when I press the notification banner, none of those callbacks are triggered.

It may be worth noting that getInitialNotification is working on iOS.

I've searched every issue and am at a loss. Any ideas what I may have improperly configured, or is anyone else experiencing this?

I'm using firebase to send the actual remote notifications.

ryanpatk avatar Apr 08 '20 21:04 ryanpatk

My NotificationService code:

export class NotificationsService {
  constructor() {
    this.messaging = messaging();
  }

  /**
   * FCM-based notification permission function for iOS. Android automatically resolves to true.
   * Potentially unused in lieu of RNNotifications permissions.
   */
  requestFCMPermission = async (): Promise<string> => {
    const granted = this.messaging.requestPermission();

    if (granted) {
      console.log('User granted messaging permissions!');
    } else {
      console.log('User declined messaging permissions :(');
    }

    return granted;
  };

  /**
   * Apps using iOS must first register the app with FCM before being able to receive messages.
   * Calling this method allows FCM to send messages to your device, however if you wish to display a
   * visible notification further steps are required.
   * On Android, no registration is required and this method successfully resolves instantly.
   */
  registerAppWithFCM = async (): Promise<void> => {
    try {
      // updated from messaging().registerForRemoteNotifications to comply with v7 deprecation warning
      const register = await this.messaging.registerDeviceForRemoteMessages();

      if (!register) {
        return;
      }
    } catch (err) {
      console.log(err);

      return;
    }
  };

  /**
   * Initial setup functions required before attaching RNN event handlers
   */
  configureRNNotifications = async (): Promise<void> => {
    Notifications.events().registerRemoteNotificationsRegistered((event: Registered) => {
      // NOTE: this token does not resemble a fcmToken on iOS! it is returning an APNS
      // token which must be converted to an fcm token via an additional POST to another service.
      // see: https://github.com/wix/react-native-notifications/issues/408#issuecomment-591734138
      // On Android this will be identical to the fcm token returned in the function above.
      console.log('(RNN) Token Received', event.deviceToken);
    });

    Notifications.events().registerRemoteNotificationsRegistrationFailed(
      (event: RegistrationError) => {
        console.log(event);
      }
    );

    // Request permissions on iOS, refresh token on Android
    await Notifications.registerRemoteNotifications();
  };

  /**
   * This method attaches all of the RNN event handlers (the notification UI elements).
   * Note: I am adding them as class properties to prevent any possible duplicate instantiations.
   */
  attachRNNotificationHandlers(): void {
    this.getInitialNotification = Notifications.getInitialNotification()
      .then(notification => {
        // parse data and do something

        console.log(`initial notification opened: ${JSON.stringify(notification)}`);
      })
      .catch(() => {
        // empty
      });

    /* This triggers when the notification is received, not opened */
    this.registerNotificationReceivedForeground = Notifications.events().registerNotificationReceivedForeground(
      (notification: Notification, completion) => {
        console.log(
          `Notification received in foreground: ${notification.title} : ${notification.body}`
        );

        completion({ alert: true, sound: true, badge: true });
      }
    );

    /* This triggers when the notification is received, not opened */
    this.registerNotificationReceivedBackground = Notifications.events().registerNotificationReceivedBackground(
      (_notification: Notification, completion) => {
        console.log('registerNotificationReceivedBackground');

        completion({ alert: true, sound: true, badge: true });
      }
    );

    /* This triggers when the notification is opened, not received */
    this.registerNotificationOpened = Notifications.events().registerNotificationOpened(
      (notification: Notification, completion: () => void): void => {
        const { payload } = notification;

        // NOTE: the docs suggest some boilerplate that throws TS errors
        console.log(`Notification opened: ${payload}`);

        completion();
      }
    );
  }

  /**
   * This is the main function for registering for push notification services which invloves
   * initializing first with react-native-firebase (FCM) and then react-native-notifications (RNN).
   *
   * Steps:
   * 1. permissions (FCM)
   * 2. FCM registration (FCM)
   * 3. getting token (FCM)
   * 4. setting up messaging handlers (RNN)
   *
   * @param saveFcmToken - the callback function for saving the fcmToken to the server
   */
  initialize = async (saveFcmToken): Promise<void> => {
    let fcmToken;

    // saving the token api call onto the class instance
    this.saveFcmToken = saveFcmToken;

    // Using the permissions util from FCM. Alternatively react-native-permissions could be used.
    const hasPermission = await this.requestFCMPermission();

    if (!hasPermission) return;

    await this.registerAppWithFCM();

    try {
      // There are reports of this not working on the first run...
      // We are using this token from FCM in lieu of the deviceToken from RNN
      fcmToken = await this.messaging.getToken();

      console.log(`(FCM) Token Received: ${fcmToken}`);
    } catch (e) {
      console.log('No Token Received Error:', e);

      return;
    }

    if (fcmToken) {
      // ... send to api
    }

    await this.configureRNNotifications();

    this.attachRNNotificationHandlers();
  };
}

and my AppDelegate.m contains:

if ([FIRApp defaultApp] == nil) {
    [FIRApp configure];
  }

  [RNNotifications startMonitorNotifications];
  
  return YES;

and

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
  [RNNotifications didRegisterForRemoteNotificationsWithDeviceToken:deviceToken];
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
  [RNNotifications didFailToRegisterForRemoteNotificationsWithError:error];
}

ryanpatk avatar Apr 08 '20 22:04 ryanpatk

Did find a way to solve this issue? I was experiencing almost the same thing in iOS. But mine doesn't receive any notification at all. But on the Android side it works as expected.

jwarrencedro avatar Apr 10 '20 09:04 jwarrencedro

I am having the same issue

alexbcasas avatar Apr 10 '20 14:04 alexbcasas

@jwarrencedro still no solution from me :(

I am able to actually receive notifications on iOS though. Its worth noting that Im using a firebase cloud messaging (fcm) token to send notifications to the device.

You can also utilize the APNS token returned from react-native-notifications to send the notifications by manually converting it into an fcm token as outlined in this comment: https://github.com/wix/react-native-notifications/issues/408#issuecomment-591734138

I have also tried using the curl method of sending a push notification directly via the APNS token (as outlined in this post: https://dev.to/jakubkoci/react-native-push-notifications-313i) to rule out firebase as the culprit of the event handlers not triggering.

I am able to successfully receive push notifications via both methods, however none of the event handler callbacks are ever invoked. I've set a bunch of log statements in the native code itself and nothing seems to trigger there either.

ryanpatk avatar Apr 10 '20 14:04 ryanpatk

Yes, the same for me, I have tried manually with Firebase Cloud Messaging and I am getting the notification (Just when the app is on background, not on foreground). However as you mention none of the handling methods are executed.

The same logic works perfectly with Android

alexbcasas avatar Apr 10 '20 15:04 alexbcasas

@AlexD10S let me know if you ever figure anything out. This is really frustrating and I don't understand the native iOS side well enough to even conceptually grasp what's missing.

A lot of people report that the iOS notifications do work so I have been thinking about what kind of environment or configuration setting might be causing this difference in observed behavior.

ryanpatk avatar Apr 13 '20 13:04 ryanpatk

Bumping this so that the inactivity bot doesn't get any ideas 😅

I feel like this is a serious issue and is impacting the ability to use this library at all.

Would love to hear even some quick thoughts from the maintainers about just generally what might be causing this.

ryanpatk avatar Apr 14 '20 15:04 ryanpatk

@AlexD10S I found a way to leverage FCM event handlers for iOS notifications... only thing is they don't work for Android 😅

So basically Im going to be using platform checks to instantiate Android event handlers using RNN, or ios event handlers using FCM. Its hacky, but thats react-native for you.

ryanpatk avatar Apr 16 '20 22:04 ryanpatk

Seeing same exact issue here, wanted to try out this library to use those callbacks but using same code as the docs they don't seem to work

aprilzero avatar Apr 21 '20 08:04 aprilzero

Experiencing the same issue as well here. Really want to avoid having to piece together th implementing with FCM since it works really well for Android.

EIrwin avatar Apr 28 '20 03:04 EIrwin

Same issue

saczuac avatar Apr 29 '20 22:04 saczuac

I know its poor form to reference another lib in the GH issues of another, but I just want to share what ended up working for me because I spent weeks dead in the water because of this problem.

Here is my implementation that uses the FCM event handler (which is semi-undocumented, make sure you're on the latest version release candidate) or the RNN event handler based on the Platform:

/*
     * This triggers when the notification is opened (foreground or background), not received.
     * Note for iOS, we are using the FCM event handler. For Android, we are using the RNN event handler.
     * TODO: If the FCM-based event handler is fixed to support android, remove the ternary here and
     * all RNN-based logic and dependencies.
     */
    this.onNotificationOpened = IS_ANDROID
      ? Notifications.events().registerNotificationOpened(
          // NOTE: the docs suggest some boilerplate that throws TS errors, see: https://github.com/wix/react-native-notifications/pull/499
          (notification: Notification, completion: () => void): void => {
            const { payload } = notification;

            // do your stuff

            completion();
          }
        )
      : this.messaging.onNotificationOpenedApp(remoteMessage => {

          // do your stuff

        });

And for the record I harbor no ill feelings toward any lib. React Native is such a complicated and community-driven ecosystem that anyone whose ever spent any time working on its open-source tooling deserves a medal and a cup of coffee :)

ryanpatk avatar Apr 30 '20 16:04 ryanpatk

I'm experiencing the exact same behavior as you described. I guess I'll go with your "fix" described for now. It might be worth noting that this.messaging.onNotificationOpenedApp(...) worked fine for both iOS and Android in my project, so I'm just going to use that for now entirely in place of Notifications.events().registerNotificationOpened(...)

bfaulk96 avatar May 18 '20 22:05 bfaulk96

I'm having the same issue.

winzazx avatar May 29 '20 08:05 winzazx

@rynatk Thanks so much for finding a work around for this, really helped me a lot!

As an addendum for anyone else finding this thread:

messaging().onNotificationOpenedApp(...)

is the workaround for BACKGROUND notifications

messaging().onMessage((remoteMessage) => {
   console.log(remoteMessage);
});

is the workaround for FOREGROUND notifications

mrarlloyd avatar Jun 05 '20 14:06 mrarlloyd

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs.

stale[bot] avatar Jul 05 '20 14:07 stale[bot]

This is certainly still an issue and should not be closed

bfaulk96 avatar Jul 06 '20 14:07 bfaulk96

Me too. I can use only three event methods.

  • registerRemoteNotificationsRegistered
  • registerRemoteNotificationsRegistrationFailed
  • getInitialNotification

tomriddle7 avatar Jul 10 '20 00:07 tomriddle7

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs.

stale[bot] avatar Aug 09 '20 01:08 stale[bot]

go away stalebot

ryanpatk avatar Aug 12 '20 19:08 ryanpatk