Home > Back-end >  Is expo token generated on real device?
Is expo token generated on real device?

Time:08-31

What im trying to do is to implement the push notification expo on my mobile app. To do that I am using the expo push token, which identifies the device to send the notification. When I tested it locally the expo token is generated but when I tried on APK, the expo token is not generated. Does the expo token work only locally and not in production, or have I missed a configuration or code?

the function that generates it:

  function startNotifications() {
    return Notifications.getExpoPushTokenAsync()
      .then(pushTokenData => {
        if (Platform.OS === 'android') {
          Notifications.setNotificationChannelAsync(ANDROID_NOTIF_CHANNEL, ANDROID_NOTIF_CONFIG);
        }
        setExpoPushToken(pushTokenData.data);
        return 'granted';
      });
  }

This function is called when the user allows notification, but in any scenarios(even if I don't ask the user and I just created it) in the APK, it won't be generated it.

How can I fix this?

CodePudding user response:

Expo is pretty well documented when it comes to push notifications. You first need to request permissions, if you don't do that you will never get a push notification token.

Here is a snippet from their official documentation, I've added comments for each of the steps:

// Don't request a token if this is a simulator
if (Device.isDevice) {

// Check to see if there is an existing permissions status
const { status: existingStatus } = await Notifications.getPermissionsAsync();

let finalStatus = existingStatus;

// If the user hasn't granted permissions, ask them if they are ok with this request
if (existingStatus !== 'granted') {
  const { status } = await Notifications.requestPermissionsAsync();
  finalStatus = status;
}

// The user has chosen not to give us permission - p.s. you shouldn't show this message to the user, it is just for testing (it can be ignored)
if (finalStatus !== 'granted') {
  alert('Failed to get push token for push notification!');
  return;
}

// The user has granted permissions, you can grab the token
token = (await Notifications.getExpoPushTokenAsync()).data;
console.log(token);

} else {
  // This isn't really important, but can help for your initial testing
  alert('Must use physical device for Push Notifications');
}

You just need to ensure that you are requesting permissions from the user before attempting to get the token - otherwise it will never be returned (unless for some weird reason the user already gave permission without being asked - which should practically be impossible).

Here is a link to the official docs: https://docs.expo.dev/versions/latest/sdk/notifications/#api, you can skip ahead to the registerForPushNotificationsAsync method.

  • Related