如何在新版react-native-onesignal中获取pushToken?
解决方法
OneSignal 新版本已经移除了旧版本的ids事件监听,你可以通过以下两种方式获取pushToken:
- 主动调用接口获取:初始化完成后直接调用异步方法
OneSignal.getDeviceState()即可拿到当前设备的pushToken,适合需要在特定时机主动查询的场景。 - 订阅权限/Token变化事件:通过
addSubscriptionObserver订阅订阅状态变更事件,只要pushToken发生更新就会触发回调,适合需要实时感知Token变化的场景。
你现有函数组件代码修改示例
useEffect(() => { // OneSignal Init Code OneSignal.setAppId("My-OneSignal-Key"); OneSignal.setLogLevel(6, 0); // END OneSignal Init Code // 方式1:初始化后主动获取pushToken OneSignal.getDeviceState().then(deviceState => { if (deviceState && deviceState.pushToken) { console.log('当前设备pushToken:', deviceState.pushToken); // 这里处理你的token逻辑,比如上报到你的服务端 } }); // 方式2:订阅token变化事件,token更新时自动触发 OneSignal.addSubscriptionObserver(event => { const { to } = event; if (to.pushToken) { console.log('更新后的pushToken:', to.pushToken); } }); // 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); }); // 组件卸载时移除订阅(可选,防止内存泄漏) return () => { OneSignal.removeSubscriptionObserver(); } }, [])
注意事项
如果用户还没有同意通知权限,获取到的pushToken会为null,建议你拿到后做非空判断再处理;如果同时使用两种方式,可以覆盖首次获取和后续token更新的所有场景。
内容的提问来源于stack exchange,提问作者SatelBill
相关产品推荐
相关产品推荐

