本地通知
getInitialNotification 不适用于本地通知。
不幸的是,从 React Native 的 0.28 开始,使用 PushNotificationIOS.getInitialNotification() 在由 Local 推送通知启动时总是返回 null 值。
因此,您需要在 AppDelegate.m 中将推送通知作为 launchOption 捕获,并将其作为 appProperty 传递给 React Native。
这是您从冷启动或从后台/非活动状态接收本地推送通知所需的全部内容。
AppDelegate.m (原生 iOS 代码)
// Inside of your didFinishLaunchingWithOptions method...
// Create a Mutable Dictionary to hold the appProperties to pass to React Native.
NSMutableDictionary *appProperties = [NSMutableDictionary dictionary];
if (launchOptions != nil) {
// Get Local Notification used to launch application.
UILocalNotification *notification = [launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey];
if (notification) {
// Instead of passing the entire Notification, we'll pass the userInfo,
// where a Record ID could be stored, for example.
NSDictionary *notificationUserInfo = [notification userInfo];
[ appProperties setObject:notificationUserInfo forKey:@"initialNotificationUserInfo" ];
}
}
// Your RCTRootView stuff...
rootView.appProperties = appProperties;
index.ios.js (反应原生)
componentDidMount() {
if (this.props.initialNotificationUserInfo) {
console.log("Launched from Notification from Cold State");
// This is where you could get a Record ID from this.props.initialNotificationUserInfo
// and redirect to the appropriate page, for example.
}
PushNotificationIOS.addEventListener('localNotification', this._onLocalNotification);
}
componentWillUnmount() {
PushNotificationIOS.removeEventListener('localNotification', this._onLocalNotification);
}
_onLocalNotification( notification ) {
if (AppState.currentState != 'active') {
console.log("Launched from Notification from Background or Inactive state.");
}
else {
console.log("Not Launched from Notification");
}
}
确保从react-native 导入PushNotificationIOS 和AppState。
我尚未使用远程推送通知对此进行测试。也许@MarkAmery 的方法适用于远程推送通知,但不幸的是,就 React Native 的当前状态而言,这是我能够从冷状态获得本地推送通知的唯一方法。
这在 React Native 中是高度无证的,所以我在他们的 GitHub 存储库上创建了 an issue 以引起人们对它的关注并希望能纠正它。如果你正在处理这个问题,那就去那里给它竖起大拇指,让它渗透到顶部。
https://github.com/facebook/react-native/issues/8580