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

Posted

技术标签:

【中文标题】如何从 react-native-onesignal 获取 pushToken?【英文标题】:How to get pushToken from react-native-onesignal? 【发布时间】: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?

【问题讨论】:

【参考方案1】:

我在the doc找到这个:

const deviceState = await OneSignal.getDeviceState();

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

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

【讨论】:

【参考方案2】:

查看setNotificationOpenedHandlersetNotificationWillShowInForegroundHandler的通知对象内部。

【讨论】:

以上是关于如何从 react-native-onesignal 获取 pushToken?的主要内容,如果未能解决你的问题,请参考以下文章

如何将数据从回收器适配器发送到片段 |如何从 recyclerview 适配器调用片段函数

如何从 Firebase 获取所有设备令牌?

如何直接从类调用从接口继承的方法?

如何从服务器获取和设置 android 中的 API(从服务器获取 int 值)?如何绑定和实现这个

如何从Mac从android studio中的fabric注销? [复制]

如何从设备中获取 PDF 文件以便能够从我的应用程序中上传?