Mark Amery Mark Amery - 3 months ago 69x
iOS Question

Detect whether React Native iOS app was opened via push notification

Detect if the app was launched/opened from a push notification describes how to detect whether a native iOS app was opened (that is, either launched or merely made active) via the user tapping a push notification.

How can I do the same thing in React Native?

lets me attach a notification listener...

PushNotificationIOS.addEventListener('notification', function (notification) {
console.log('got a notification', notification);

but this fires both when a push notification is received with the application in the foreground, and when I open the app via a push notification.

How can I detect the second case in particular?


There are two cases here that need to be detected in different ways:

  1. The app has been completely terminated and is being launched by a user's tap on a push notification. This can be detected (and the notification's data acquired) via the React.PushNotificationIOS.popInitialNotification method.
  2. The app had been suspended and is being made active again by a user's tap on a push notification. Just like in a native app, you can tell that this is happening because iOS passes the tapped notification to your app when it is opening (even if it's an old notification) and causes your notification handler to fire while your app is in UIApplicationStateInactive state (or 'background' state, as React Native's AppStateIOS class calls it.

Code to handle both cases (you can put this in your index.ios.js or somewhere else that's run on app launch):

import React from 'react-native';
var {PushNotificationIOS, AppStateIOS} = React;

function appOpenedByNotificationTap(notification) {
  // This is your handler. The tapped notification gets passed in here.
  // Do whatever you like with it.

let launchNotification = PushNotificationIOS.popInitialNotification();

if (launchNotification) {

let backgroundNotification;

PushNotificationIOS.addEventListener('notification', function (notification) {
  if (React.AppStateIOS.currentState === 'background') {
    backgroundNotification = notification;

React.AppStateIOS.addEventListener('change', function (new_state) {
  if (new_state === 'active' && backgroundNotification != null) {
    backgroundNotification = null;