Detect whether React Native iOS app was opened via push notification

后端 未结 3 594
栀梦
栀梦 2020-12-13 07:41

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) v

3条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-13 07:42

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

    1. The app has been completely terminated (e.g. by restarting the phone, or by double-tapping home and swiping it off the list of apps running in the background) 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.getInitialNotification 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';
    import { PushNotificationIOS, AppState } from 'react-native';
    
    function appOpenedByNotificationTap(notification) {
      // This is your handler. The tapped notification gets passed in here.
      // Do whatever you like with it.
      console.log(notification);
    }
    
    PushNotificationIOS.getInitialNotification().then(function (notification) {
      if (notification != null) {
        appOpenedByNotificationTap(notification);
      }
    });
    
    let backgroundNotification;
    
    PushNotificationIOS.addEventListener('notification', function (notification) {
      if (AppState.currentState === 'background') {
        backgroundNotification = notification;
      }
    });
    
    AppState.addEventListener('change', function (new_state) {
      if (new_state === 'active' && backgroundNotification != null) {
        appOpenedByNotificationTap(backgroundNotification);
        backgroundNotification = null;
      }
    });
    

提交回复
热议问题