Expo Notifications.registerTaskAsync not running defined task

99 views Asked by At

I am trying to have a sound play when a notification is received from my application while my application is in the background.

I have followed the expo documentation but can not get the code within my task to execute when the notification is received

I am using the example from the expo documentation to test I am also using an eas build and am testing on a physical iOS device

Registering my task

import { Button, Platform, Text, View } from "react-native";
import * as Device from "expo-device";
import { useEffect, useRef, useState } from "react";
import * as Notifications from "expo-notifications";
import { NotificationResponse } from "expo-notifications";
import * as TaskManager from "expo-task-manager";
import RNSystemSounds from "@dashdoc/react-native-system-sounds";

TaskManager.defineTask(
  BACKGROUND_NOTIFICATION_TASK,
  ({ data, error, executionInfo }) => {
    console.log("Received a notification in the background!");
    RNSystemSounds.beep();
  },
);

Notifications.registerTaskAsync(BACKGROUND_NOTIFICATION_TASK);

export default function App() {
 //app contents
}

And the code used to register for push notifications along with scheduling the notification

async function schedulePushNotification() {
  await Notifications.scheduleNotificationAsync({
    content: {
      title: "You've got mail! ",
      body: "Here is the notification body",
      data: { data: "goes here", "content-available": 1 },
      sound: true,
    },
    trigger: { seconds: 2 },
  });
}

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;
    }
    // Learn more about projectId:
    // https://docs.expo.dev/push-notifications/push-notifications-setup/#configure-projectid
    token = (
      await Notifications.getExpoPushTokenAsync({
        projectId: "09f21daf-0392-4eae-a4c0-ab9a7f27e002",
      })
    ).data;
    console.log(token);
  } else {
    alert("Must use physical device for Push Notifications");
  }

  return token;
}

Appreciate any help or guidance :)

0

There are 0 answers