ios icon indicating copy to clipboard operation
ios copied to clipboard

How to get the token after the registration is over?

Open kovkev opened this issue 3 years ago • 6 comments

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

kovkev avatar Feb 06 '22 22:02 kovkev

I don't know specifics of this library, but usually you would send the token to a server for storage upon first retrieval.

artdevgame avatar Feb 08 '22 19:02 artdevgame

Please I too have the same concern. How do I get the token to be sent to the server?

ogbodo avatar Jul 27 '22 08:07 ogbodo

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

bastengao avatar Aug 08 '22 07:08 bastengao

I need to grab the token and send back to my server. How do I do that with this current solution @bastengao

ogbodo avatar Aug 08 '22 09:08 ogbodo

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.

artdevgame avatar Aug 20 '22 09:08 artdevgame

Ok, thank you @artdevgame I will try it out and let you know the outcome.

ogbodo avatar Aug 20 '22 11:08 ogbodo