Encountering a snag when trying to grant notification permission in the Expo app

I am experiencing an issue with a simple code that previously asked for notification permissions. However, I am now encountering the following error:

"Error: Encountered an exception while calling native method: Exception occurred while executing exported method requestPermissionsAsync on module ExpoNotificationPermissionsModule: String resource ID #0xffffffff"

Here is the code in question:

    if (isDevice) {
        const { status: existingStatus } = await Notifications.getPermissionsAsync();
        let finalStatus = existingStatus;
        if (existingStatus !== "granted") {
            const { status } = await Notifications.requestPermissionsAsync();
            finalStatus = status;
        }
        if (finalStatus !== "granted") {
            Alert.alert("Falha ao obter permissão para notificações push!", "É necessário permitir o envio de notificações push para o aplicativo funcionar corretamente.");
            return "";
        }
        token = (await Notifications.getExpoPushTokenAsync()).data;
    } else {
        alert("Para gerar o token de notificação você precisa estar em um dispositivo físico!");
    }

Answer №1

When using Android 13, application users are now required to actively choose to receive notifications by responding to a permissions prompt that is automatically generated by the operating system. This prompt will only show up once at least one notification channel has been established. It is crucial to call setNotificationChannelAsync before attempting to obtain a push token with getDevicePushTokenAsync or getExpoPushTokenAsync. For more details on the updated notification permission process for Android 13, refer to the official documentation.

async function registerForPushNotificationsAsync() {
  let token;

  if (Platform.OS === 'android') {
    await Notifications.setNotificationChannelAsync('default', {
      name: 'default',
      importance: Notifications.AndroidImportance.MAX,
      vibrationPattern: [0, 250, 250, 250],
      lightColor: '#FF231F7C',
    });
  }

  if (Device.isDevice) {
    const { status: existingStatus } = await Notifications.getPermissionsAsync();
    let finalStatus = existingStatus;
    if (existingStatus !== 'granted') {
      const { status } = await Notifications.requestPermissionsAsync();
      finalStatus = status;
    }
    if (finalStatus !== 'granted') {
      alert('Failed to get push token for push notification!');
      return;
    }
    token = (await Notifications.getExpoPushTokenAsync()).data;
    console.log(token);
  } else {
    alert('Must use physical device for Push Notifications');
  }

  return token;
}

To resolve any issues related to permission prompts, it is recommended to clear storage data and uninstall the Expo Go app. Reinstalling the app should trigger the permission prompt accordingly.

Answer №2

Similar situation happened to me as well, where the notification feature was functioning properly until a recent time. Without even delving into the specific section of code responsible for handling notifications, I realized that the issue might not lie within the codebase itself. Upon further investigation, I discovered that my phone had undergone a recent OS update. In response, I took the step of uninstalling Expo and clearing all the associated app data and storage. Additionally, I made sure to update expo-cli and reverted back to the original, untouched version of the codebase on the same device. This led to a prompt for notification permissions and successfully resolved that particular aspect of the code. However, it appears that secure storage is currently facing issues. Regardless, this process may serve as a helpful starting point for troubleshooting on your end.

Answer №3

After uninstalling Expo Go and doing a fresh reinstall, everything worked perfectly for me. I also made sure to update the expo-cli by running "npm install -g eas-cli". Hopefully this solution will be helpful for others facing similar issues.

Answer №4

After following Irfan Muhammad's advice, I decided to relocate the registerForPushNotificationsAsync function to the beginning of my App.js file. Then, I uninstalled expo go and installed it again as instructed.

I cannot be certain if moving the function had any impact, but it is the step that I took. Surprisingly, the prompt appeared right away after making these adjustments.

Answer №5

If you're looking to resolve this issue, make sure to check out the following guide: expo notification setup

  • Include the code below if it's not already present
  if (Platform.OS === 'android') {
    await Notifications.setNotificationChannelAsync('default', {
      name: 'default',
      importance: Notifications.AndroidImportance.MAX,
      vibrationPattern: [0, 250, 250, 250],
      lightColor: '#FF231F7C',
    });
  }
  • Remember to add the projectId within the getExpoPushTokenAsync function
  token = (
      await Notifications.getExpoPushTokenAsync({
        projectId: Constants.expoConfig.extra.eas.projectId,
      })
  • Enclose the entire code block in a try-catch statement to catch any potential issues that may arise in the future

Answer №6

The advice given by @sreedeep regarding FCM is valuable, suggesting the use of getDevicePushTokenAsync rather than getExpoPushTokenAsync. You can find more details about this recommendation here

Answer №7

If you're having trouble with the Expo Go app, try clearing its storage and then relaunching the app. This simple fix has worked for me in the past.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Can we limit the return type of arrow function parameters in TypeScript?

Within my typescript code, there is a function that takes in two parameters: a configuration object and a function: function executeMaybe<Input, Output> ( config: { percent: number }, fn: (i: Input) => Output ): (i: Input) => Output | &apos ...

Engaging Resources for Introducing Children to Javascript Programming

Anyone have recommendations for a physical book designed to help children learn programming using Javascript? I've come across the question "Best ways to teach a beginner to program" on Stack Overflow, but it's more focused on Python and doesn&a ...

Assign the JSON string to a variable

As a Linux sysadmin with limited coding skills, I took on the challenge of creating a demo RCS chatbot in nodejs that mirrors any message it receives. Surprisingly, I made it pretty far, but now I need help with the final step. I'm really enjoying thi ...

Angular backslash is encoded

Experiencing the same issue as this individual: angularjs-slash-after-hashbang-gets-encoded The URL is getting encoded and not routing correctly, causing it to fall to the otherwise in my route config. I have not been able to identify the root cause yet, ...

A step-by-step guide on sending a fetch request to TinyURL

I have been attempting to send a post request using fetch to tinyURL in order to shorten a URL that is generated on my website. The following code shows how I am currently writing the script, however, it seems like it's not returning the shortened URL ...

Error: Cannot locate 'import-resolver-typescript/lib' in jsconfig.json file

Issue: An error occurred stating that the file '/Users/nish7/Documents/Code/WebDev/HOS/frontend/node_modules/eslint-import-resolver-typescript/lib' could not be found. This error is present in the program because of the specified root file for c ...

Failure to Present Outcome on Screen

Seeking assistance! I attempted to create a mini loan eligibility web app using JavaScript, but encountered an issue where the displayed result did not match the expected outcome upon clicking the eligibility button. Here is the HTML and JavaScript Code I ...

The Mongoose model is having issues being imported into a different Component

Attempting to utilize my model for displaying and locating users in MongoDB has hit a snag. Upon importing it into profile.js and launching my app, an error is thrown: Cannot read properties of undefined (reading 'Users') https://i.stack.imgur.c ...

JSON input in react.js sadly ended abruptly

I am encountering a problem when I attempt to submit the form. Unhandled Rejection (SyntaxError): Unexpected end of JSON input Whenever I press the submit button, this error occurs, here is the code snippet: onButtonSubmit = () => { this.setState({ ...

Global Positioning System (GPS) tracking combined with accelerometer

Is utilizing the accelerometer to detect movement a practical approach to conserve battery power while running a service that checks and transmits GPS data? Or is the onLocationChanged method already efficient enough on its own, making the use of the accel ...

What is the best way to exclude an external HTML file from being displayed on the home page?

shopping_cart.php <div id="main-container"> <div class="container"> <span class="top-label"> <span class="label-txt">Shopping Cart</span> </span> <div class="content-area"> <div class="con ...

Setting the base URL in Next.js according to an environment variable: a step-by-step guide

I currently have a Strapi backend and Next.js frontend application deployed on DigitalOcean. Within DigitalOcean, I have configured an environment variable for the frontend: API_URL = ${APP_URL}/api To generate the base URL, I retrieve this variable using ...

What steps should I take to ensure that the proper link is loaded and opened when the loop is clicked?

I've been working on a script to display the top 25 posts from reddit and have their respective links open in a sliding div below. However, I'm running into an issue where the script outputs the same post for every item in the loop. I understand ...

405 error: NGINX blocking POST method in Django DRF Vue.js application

I have encountered a strange issue while building my ecommerce site. Everything seems to be working fine, except for the forms. When attempting to post content, I keep receiving a 405 method get not allowed error. It's confusing as I am trying to use ...

Having trouble with jQuery.cookie saving my JSON data

Being new to jQuery and JSON, I find this situation quite frustrating as it seems pretty straightforward but still doesn't work for me. My ASP.NET MVC website is using AJAX (via jQuery) to load data. Everything works fine until this point. I'm ...

React Chart.js allows for consistent spacing for x-axes by displaying dates in a well-organized

After incorporating displayFormats in scales.x, I noticed that my xAxes labels are spaced differently based on the data object they contain. How can I adjust my xAxes labels to have equal spacing? The code snippet is displayed in the following image. Pleas ...

Picasso encountered a problem when trying to process a list of images

While working on parsing a list of images from JSON data and displaying them using Picasso based on user click position, I encountered this error: FATAL EXCEPTION: main java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0 at java.util ...

Error: A stream was expected, but instead you provided an object that is invalid. Acceptable options include an Observable, Promise, Array, or Iterable

I attempted to use map with a service call and encountered an error. After checking this post about 'subscribe is not defined in angular 2', I learned that for subscribing, we need to return from within the operators. Despite adding return statem ...

Error: HTMLAnchorElement.linkAction is attempting to access an undefined property 'add', resulting in an uncaught TypeError

Displaying the following: Error: Cannot read property 'add' of undefined at HTMLAnchorElement.linkAction const navigationLinks = document.querySelectorAll('.nav__link') function handleLinkAction(){ // Activate link navLin ...

The Axios GET request was not functioning properly after attempting to use Axios stream.on("data")

I am working with a backend API that has an endpoint named /subscribe, which gives back a continuous stream of data. Along with this, I have a node process, and I am utilizing axios to send a request to my backend API with a response type of "stream& ...