Detect if the app was launched/opened from a push notification描述了如何通过用户点击推送通知来检测是否打开了原生iOS应用程序(即启动或仅仅是激活的).
如何在React Native中做同样的事情? PushNotificationIOS
让我附上一个通知侦听器…
PushNotificationIOS.addEventListener('notification',function (notification) { console.log('got a notification',notification); });
但是当在前台接收到应用程序的推送通知时,以及当我通过推送通知打开应用程序时,这会触发.
特别是如何检测第二种情况?
这里有两种情况需要以不同的方式进行检测:
>应用程序已完全终止(例如重新启动手机,或双击家中,并从后台运行的应用程序列表中将其滑动),并由用户点击推送通知启动.这可以通过React.PushNotificationIOS.getInitialNotification
方法检测(和通知的数据).
>该应用已被暂停,并被用户点击推送通知再次激活.只要like in a native app,你可以知道这是发生的,因为iOS在开启时将启动的通知传递给你的应用程序(即使是旧的通知),并且当您的应用程序处于UIApplicationStateInactive状态(或“后台”状态,作为React Native的AppStateIOS
类调用它).
处理这两种情况的代码(您可以将其放在index.ios.js或应用程序启动时运行的其他位置):
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. console.log(notification); } PushNotificationIOS.getInitialNotification().then(function (notification) { if (notification != null) { appOpenedByNotificationTap(notification); } }); 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) { appOpenedByNotificationTap(backgroundNotification); backgroundNotification = null; } });