After reading all posts I still cannot understand how I can send a push notification to a specific user with expo

  1. Platforms(Android/iOS/web/all): React Native (IOS target)

Hi,

I am trying to build a way to send push notifications ( it’s basically an app simillar to any datting app where you click a user and it sends them a notification to let them know I want to connect).

The notifications are being received fine but I don’t know how to target a specific individual? Do I need backend for this?

This is my code:

const ProfilesScreen: React.FC<Props> = ({ navigation, route }) => {
  const [expoPushToken, setExpoPushToken] = useState("");
  const [notification, setNotification] = useState(false);
  const [notificationRes, setNotifcationRes] = useState([]);
  const notificationListener = useRef();
  const responseListener = useRef();
  const [data, setData] = useState<any>([]);
  const [notificationsSentUids, setNotificationSentUids] = useState<any>([]);
  const [notificationsCount, setNotificationsCount] = useState<number>(0);
  const [activeIndex, setActiveIndex] = useState<number>(0);
  const [storageData, setStorageData] = useState({});

  async function sendPushNotification(expoPushToken) {
    const message = {
      to: expoPushToken,
      sound: "default",
      title: "My message",
      body: storageData
        ? `${storageData?.name} wants to connect with you`
        : null,
      data: { someData: "goes here" },
    };
    await fetch("https://exp.host/--/api/v2/push/send", {
      method: "POST",
      headers: {
        Accept: "application/json",
        "Accept-encoding": "gzip, deflate",
        "Content-Type": "application/json",
      },
      body: JSON.stringify(message),
    });
  }
  async function registerForPushNotificationsAsync() {
    let token;
    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);
      setExpoPushToken(token);
    } else {
      // alert("Must use physical device for Push Notifications");
    }
    return token;
  }
  useEffect(() => {
    registerForPushNotificationsAsync().then(token => setExpoPushToken(token));
    // This listener is fired whenever a notification is received while the app is foregrounded
    notificationListener.current =
      Notifications.addNotificationReceivedListener(notification => {
        setNotification(notification);
      });

    // This listener is fired whenever a user taps on or interacts with a notification (works when app is foregrounded, backgrounded, or killed)
    responseListener.current =
      Notifications.addNotificationResponseReceivedListener(response => {
        console.log("res", response);
        setNotifcationRes(response);
    return () => {
      Notifications.removeNotificationSubscription(
        notificationListener.current
      );
      Notifications.removeNotificationSubscription(responseListener.current);
    };
  }, []);
  return .... 
};

I am new to expo + mobile dev. I am also having difficulty with notifications, however, I think I can help point you in the right direction.
Be mindful of the different types of notifications, local and push. What you want is push, which means yes you will need a backend. Where are you storing the different profiles? I.e. when an app loads a list of profiles, it must be pulling this from a backend? When an app first loads, it should register its notification token. Send this token back to your backend and store. Associate the token with the profile. Some people use firebase storage for this, and leave it all to that, but you can do this many ways. When the user clicks connect to another profile, this must upload to the backend, which in turn can cross reference that user with their notification token and send them a notification. Good luck, its quite a tricky setup!!

1 Like

hi @askariblue

sorry you are having issues too :grimacing:

Hope you can sort it!

Really appreciate your answer, I actually have firebase real time database set up for chats so I suppose it just works similar?

My only concern is the background notification which I don’t think I have set up, where basically the user is not on the app but still gets notified.

Would be nice to have a code example to refer to, using firebase, if you come across any let me know

That isnt too bad setting up and the documentation is pretty clear.
First allow for notifications.
Then get token.
Send token to your backend.
Send push notification, via FCM does seem to be best, see documentation. This can be tricky.
Setup listeners, one for when app is in fore/background (this is pretty easy) or killed/closed (this is proving tricky)

If I understood you correctly, you want to send notification to ppl without the app? i dont see how this works, you wouldnt have obtained a token and therefore nowhere to send it.

Hey,

I thought FCM was for Android only, I am targetting IOS atm. Will take a better look at the docs though.

It seems pretty straight forward as you explain it.

No, people have the app, just not open. Same as whatsapp for example. You might not have the app open but you still get notified if a new message arrives.

oh yes, might be getting confused. Anyway we use expo to send the notifications who in turn send to firebase + apple.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.