如何在Expo Firebase中向特定用户发送推送通知

时间:2019-08-06 12:20:23

标签: firebase react-native notifications

我正在与Expo进行本地和Firebase的交互,并且我想从Internet或EXPO文档中获得足够的帮助。请告诉我如何向特定用户发送点击推送通知

2 个答案:

答案 0 :(得分:0)

您可以使用expo的Notifications.getExpoPushTokenAsync();方法来获取推送令牌,然后可以通过向此端点https://your-server.com/users/push-token发出发布请求,将该推送令牌用于向该用户发送通知。

  

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

您可以这样发出请求:

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

答案 1 :(得分:0)

很简单-我为此创建了一些“服务”,请按照我的代码进行操作:

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;
}

您保存了令牌,并且当您要发送推送通知时,可以使用以下令牌调用sendPushNotification函数:

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