对于本地通知
getInitialNotification
不与本地通知工作。
不幸的是,从0开始。28 React Native,使用PushNotificationIOS.getInitialNotification()
始终会返回一个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
作为一个补充,你可能想要在状态中存储对你的处理程序的引用,并调用'componentWillUnmount'中的'removeEventListener'(如果你在一个组件中这样做) – ComethTheNerd
@ mark-amery在这种情况下应该使用哪种方法? componentWillMount? –
@NimilaHiranya它不一定需要任何方法;你可以把它放在你的'index.ios.js'文件中。但是像根视图的'componentWillMount'这样的生命周期函数也可能是一个合理的地方。 –