【问题标题】:How to get pushToken from react-native-onesignal?如何从 react-native-onesignal 获取 pushToken?
【发布时间】:2021-09-03 17:43:51
【问题描述】:

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?

【问题讨论】:

    标签: react-native push-notification onesignal react-native-onesignal


    【解决方案1】:

    我在the doc找到这个:

    const deviceState = await OneSignal.getDeviceState();
    

    所以我认为它可能是这样的:

    const deviceState = (await OneSignal.getDeviceState()).pushToken;
    

    【讨论】:

      【解决方案2】:

      查看setNotificationOpenedHandlersetNotificationWillShowInForegroundHandler的通知对象内部。

      【讨论】:

        猜你喜欢
        • 2023-01-28
        • 1970-01-01
        • 1970-01-01
        • 2018-11-21
        • 2021-08-09
        • 1970-01-01
        • 1970-01-01
        • 2020-02-19
        • 2017-12-13
        相关资源
        最近更新 更多