使用 react native 获取设备令牌
有什么方法可以通过 React Native 按需获取通知的设备令牌?从文档来看,似乎唯一公开令牌的时间是在 PushNotification 注册事件上.
Is there any way to get the device token for notifications on demand with react native? It seems, from the docs, like the only time the token is exposed is on the PushNotification register event.
更一般地说,处理设备令牌的常见做法是什么?
More generally, what's the common practice for handling device tokens?
如果一个用户登录我的应用程序,该应用程序会从 PushNotification 请求权限,注册事件被触发,我可以将该设备与登录用户相关联.到目前为止一切顺利,但是如果该用户注销,并且我打破该关联以停止通知,当另一个用户登录时我该怎么办?该应用程序已经拥有权限,因此注册不会再次触发.如何获取设备令牌以将其与新用户关联?
If one user logs into my app, the app requests permissions from PushNotification, the register event is fired and I can associate that device with the logged in user. So far so good, but if that user logs out, and I break that association to stop the notifications, what do I do when another user logs in? The app already has permissions, so register won't fire again. How do I get the device token to associate it with the new user?
还是我想错了?
看来我的假设是 register
事件仅在用户授予访问权限时触发是问题所在.无论是否提示用户,register
事件都会响应对 requestPermissions
的调用而触发.因此,通过在应用加载时请求权限并响应 register
事件,您始终可以获取设备 ID.像这样:
It seems my assumption that the register
event only fires when the user grants access was the problem. The register
event will fire in response to a call to requestPermissions
whether or not the user was prompted. So by requesting permissions and responding to the register
event when the app loads, you can always get the device id. Like so:
PushNotificationIOS.addEventListener('register', (token) => {
... store or use the token here ...
});
PushNotificationIOS.requestPermissions();