Muhammad Haseeb
Muhammad Haseeb

Reputation: 31

How to send push notification to specific user in Expo Firebase

I'm working with Expo react native and firebase and i'm noting getting enough help from internet or expo docs.Please tell me how to send on click push notification to specific user

Upvotes: 2

Views: 4882

Answers (2)

Idan
Idan

Reputation: 4023

Is simple - i create some 'service' for this, follow my code:

import * as firebase from 'firebase';
import { Permissions, Notifications } from 'expo';

export const registerForPushNotificationsAsync= async() => {
settings = {}
try{
    const { status: existingStatus } = await Permissions.getAsync(Permissions.NOTIFICATIONS);
    let finalStatus = existingStatus;
    // only ask if permissions have not already been determined, because iOS won't necessarily prompt the user a second time.
    if (existingStatus !== 'granted') {
        // Android remote notification permissions are granted during the app install, so this will only ask on iOS
        const { status } = await Permissions.askAsync(Permissions.NOTIFICATIONS);
        finalStatus = status;
    }
    // Stop here if the user did not grant permissions
    if (finalStatus !== 'granted')
        settings['token'] = ''
    else{
        // Get the token that uniquely identifies this device
        let token = await Notifications.getExpoPushTokenAsync();
        settings['token'] = token
    }
    settings['status'] = finalStatus
}
catch(e){
    settings['token'] = '' 
    settings['status'] = ''
    console.log('error notification ',e)
}
    return settings;
}

You save the token and when you want to send push notification you call sendPushNotification function with this token:

export const sendPushNotification = (token, title, body) => {
    return fetch('https://exp.host/--/api/v2/push/send', {
      body: JSON.stringify({
        to: token,
        title: title,
        body: body,
        data: { message: `${title} - ${body}` },
        sound: "default",
        icon: "/assets/images/lionIcon180-180.png",
        android:{
            icon: "/assets/images/lionIcon180-180.png",
            sound:"default"
        }
      }),
      headers: {
        'Content-Type': 'application/json',
      },
      method: 'POST',
    });
}

Upvotes: 2

fayeed
fayeed

Reputation: 2485

You can use the expo's Notifications.getExpoPushTokenAsync(); method to get the push token which you can then use to send a notification to that user later by making a post request to this endpoint https://your-server.com/users/push-token.

https://docs.expo.io/versions/latest/guides/push-notifications/

You could make a request like so:

fetch(PUSH_ENDPOINT, {
    method: 'POST',
    headers: {
      Accept: 'application/json',
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      token: {
        value: "PUSH_TOKEN_OF_USER",
      },
      user: {
        username: 'Jhon',
      },
    }),
  })

Upvotes: 0

Related Questions