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

问题描述 投票:0回答:4

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
4个回答
3
投票

getDeviceState 不再是最新 OneSignal v5.0.3 上的函数。 以下是在用户接受权限后获取订阅 ID 和订阅令牌的方法:

const subId = OneSignal.User.pushSubscription.getPushSubscriptionId();
const subToken = OneSignal.User.pushSubscription.getPushSubscriptionToken();

1
投票

我在文档中找到了这个:

const deviceState = await OneSignal.getDeviceState();

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

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

0
投票

适用于 v5.2.6

尝试

  import {OneSignal} from 'react-native-onesignal';
  const fetchOneSignalID = async () => {
    try {
      const oneSignalID = await OneSignal.User.getOnesignalId();
      console.log('oneSignalID', oneSignalID);
    } catch (error) {
      console.error('Error fetching OneSignal ID', error);
    }
  };

  useEffect(() => {
    fetchOneSignalID();
  }, []);


-1
投票

查看

setNotificationOpenedHandler
setNotificationWillShowInForegroundHandler
的通知对象内部。

© www.soinside.com 2019 - 2024. All rights reserved.