繁体   English   中英

如何从 react-native-onesignal 获取 pushToken?

[英]How to get pushToken from react-native-onesignal?

1 年前,我在我的 react-native 应用程序中成功获得了 pushToken。 但是现在官网示例代码改了,找不到pushToken的代码。

这是我去年使用的代码。 (类组件)

constructor(props) {
    super(props);
    ...
    OneSignal.addEventListener('ids', this.onIds);
}
componentWillUnmount() {
    OneSignal.removeEventListener('received', this.onReceived);
    OneSignal.removeEventListener('opened', this.onOpened);
    OneSignal.removeEventListener('ids', this.onIds);
}
onIds(device) {
    console.log('Device info: ', device);  // I got pushToken here successfully last year.
}

这是我目前的代码。 (功能组件)

useEffect(() => {
    // OneSignal Init Code
    OneSignal.setAppId("My-OneSignal-Key");
    OneSignal.setLogLevel(6, 0);
    // END OneSignal Init Code

    // Prompt for push on iOS
    OneSignal.promptForPushNotificationsWithUserResponse(response => {
        console.log("Prompt response:", response);
    });

    // Method for handling notifications received while app in foreground
    OneSignal.setNotificationWillShowInForegroundHandler(notificationReceivedEvent => {
        console.log("OneSignal: notification will show in foreground:", notificationReceivedEvent);
        let notification = notificationReceivedEvent.getNotification();
        console.log("notification: ", notification);
        const data = notification.additionalData
        console.log("additionalData: ", data);
        // Complete with null means don't show a notification.
        notificationReceivedEvent.complete(notification);
    });

    // Method for handling notifications opened
    OneSignal.setNotificationOpenedHandler(notification => {
        console.log("OneSignal: notification opened:", notification);
    });
}

但是现在,我应该从哪里获得 pushToken?

谢谢杰里米 :)

我在文档中找到了这个:

const deviceState = await OneSignal.getDeviceState();

所以我认为它可能是这样的: const deviceState = (await OneSignal.getDeviceState()).pushToken;

基于此链接: https : //documentation.onesignal.com/v7.0/docs/react-native-sdk

查看setNotificationOpenedHandlersetNotificationWillShowInForegroundHandler的通知对象内部。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM