如何使用react-native的PushNotificationIOS.getInitialNotification

时间:2016-07-28 19:29:07

标签: javascript push-notification react-native

我正在尝试检测用户点击推送通知横幅是否启动了我的本机反应应用程序(请参阅该主题的this excellent SO answer)。

我已经实现了Mark描述的模式,并且发现PushNotificationIOS.getInitialNotification提供的“通知”对象非常奇怪,至少在没有检索通知的情况下。检测到这个案例一直是PITA,我其实很困惑。

据我所知,PushNotificationIOS.getInitialNotification返回一个承诺;当没有通知等待用户时,此承诺应该使用null或实际通知对象 - null来解决。这是我试图检测和支持的场景。

这就是为什么要检测到这种痛苦的原因;当没有通知要查找时,以下测试全部运行:

// tell me about the object
JSON.stringify(notification);
//=> {}

// what keys does it have?
Object.keys(notification);
//=> [ '_data', '_badgeCount', '_sound', '_alert' ]

所以它字符串化为空,但它有四个键? ķ...

// tell me about the data, then
JSON.stringify(notification._data);
//=> undefined
// wtf?

这些奇怪的事实使我的理解和区分实际通知响应的情况与邮箱为空的情况的能力受挫。基于这些事实,我认为我可以测试我想要的成员,但即使是最谨慎的探测也会在100%的时间内产生误报:

PushNotificationIOS.getInitialNotification()
.then((notification) => {

    // usually there is no notification; don't act in those scenarios
    if(!notification || notification === null || !notification.hasOwnProperty('_data')) {
        return;
    }

    // is a real notification; grab the data and act.

    let payload = notification._data.appName; // TODO: use correct accessor method, probably note.data() -- which doesn't exist
    Store.dispatch(Actions.receivePushNotification(payload, true /* true = app was awaked by note */))
});

每次运行此代码时,由于let payload,它无法触发转义加盖并抛出undefined is not an object (evaluating 'notification._data.appName')

有人可以解释这里发生了什么吗? PushNotificationIOS.getInitialNotification被破坏或弃用了吗?如何在JS中使用一个评估为undefined的键?我该如何检测这种情况?

经验丰富的javascripter,非常困惑。谢谢你的帮助。

BTW:使用react-native v0.29.0

1 个答案:

答案 0 :(得分:2)

notificationan instance of PushNotification,而不是普通对象,这就是为什么它将字符串化为空对象,因为没有为它实现自定义toString。

对我来说这听起来像是一个错误(如果还没有,应该报告),当没有通知时,会创建该对象。

无论如何,要解决此问题,您的检查应该是:

if(!notification || !notification.getData()) {
        return;
}

更新:问题已在0.31中修复 - 有关详细信息,请参阅Github issue