这里有两种情况需要以不同的方式检测:
- 应用程序已完全终止(例如,重新启动手机,或双击home并将其从后台运行的应用程序列表中删除),用户点击推送通知后,应用程序将被终止.这可以通过
React.PushNotificationIOS.getInitialNotification
方法检测(以及获取通知的数据).
- 该应用程序已暂停,用户点击推送通知后将再次激活.只有like in a native app个,你可以看出这是因为iOS在应用程序打开时将点击的通知传递给你的应用程序(即使它是一个旧的通知),并在你的应用程序处于
UIApplicationStateInactive
状态(或'background'
状态,React Native的AppStateIOS
类称之为'background'
状态)时触发通知处理程序.
处理这两种情况的代码(你可以把它放在你的index.ios.js
或应用程序启动时运行的其他地方):
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;
}
});