ios
ios copied to clipboard
How to get the token after the registration is over?
Say the user has already allowed push notifications and the "register" function had already been called. How can we, at a later time, get the token?
I look at AppDelegate.m and it doesn't seem to be a function like "onStartup" that gets the token and passes it to the library
I don't know specifics of this library, but usually you would send the token to a server for storage upon first retrieval.
Please I too have the same concern. How do I get the token to be sent to the server?
My solution.
PushNotificationIOS.checkPermissions(permissions => {
if (
permissions.authorizationStatus ===
PushNotificationIOS.AuthorizationStatus
.UNAuthorizationStatusAuthorized
) {
// requestPermissions will trigger registerForRemoteNotifications implicitly.
// register listener will get device token.
PushNotificationIOS.requestPermissions({
alert: true,
badge: true,
sound: true,
});
}
});
https://github.com/react-native-push-notification/ios/blob/f2f28cf08f0b6b3f97a3ce799d7b1a662e59edf5/ios/RNCPushNotificationIOS.m#L231
I need to grab the token and send back to my server. How do I do that with this current solution @bastengao
I need to grab the token and send back to my server. How do I do that with this current solution @bastengao
async function registerDevice(deviceToken) {
const res = await fetch('http://your-device-registering-service.com', {
method: 'post',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ deviceToken })
})
if (!res.ok) {
throw new Error(`Failed to register device with service: ${deviceToken}`)
}
}
useEffect(() => {
PushNotificationIOS.addEventListener('register', registerDevice);
return () => {
PushNotificationIOS.removeEventListener('register');
}
}, [])
Note: I haven't tested this code (just typed it into the comment box), but should give you some idea of what I was thinking. Also, this bit goes in the javascript side of things, incase that isn't clear.
Ok, thank you @artdevgame I will try it out and let you know the outcome.