简体   繁体   中英

How to send push notification to specific user in Expo Firebase

我正在与Expo React Native和Firebase一起工作,并且我注意到从Internet或EXPO文档获得了足够的帮助。请告诉我如何向特定用户发送点击推送通知

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',
      },
    }),
  })

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',
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM