react-native-push-notification / ios

React Native Push Notification API for iOS.
MIT License
732 stars 281 forks source link

How to get the token after the registration is over? #353

Open kovkev opened 2 years ago

kovkev commented 2 years ago

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

artdevgame commented 2 years ago

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

ogbodo commented 1 year ago

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

bastengao commented 1 year ago

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

ogbodo commented 1 year ago

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

artdevgame commented 1 year ago

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.

ogbodo commented 1 year ago

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