使用Expo发送推送通知

时间:2019-06-25 10:00:59

标签: react-native push-notification expo

我正在尝试使用Expo发送推送通知,但是我收到了。但是在我的设备上也没有振动或声音,也没有弹出窗口。我正在将Galaxy S9与Android 9配合使用。我尚未在Iphone上尝试过。

推送通知由nodejs发送,安装该应用程序的用户将收到推送通知。用户expo令牌保存在firebase数据库中。我成功保存并获取了令牌。

以下是来自博览会应用程序

class App extends Component {
  componentWillMount() {
    firebase.initializeApp(config);
    this.registerForPushNotificationsAsync();
  }
  async registerForPushNotificationsAsync(){
    const { status: existingStatus } = await Permissions.getAsync(
      Permissions.NOTIFICATIONS
    );
    let finalStatus = existingStatus;

    if (Platform.OS === 'android') {
      Notifications.createChannelAndroidAsync('chat-messages', {
        name: 'Chat messages',
        sound: true,
        priority: 'high', // was max
        vibrate: [0, 250, 250, 250],
      });
    }
    if (existingStatus !== 'granted') {

      const { status } = await Permissions.askAsync(Permissions.NOTIFICATIONS);
      finalStatus = status;
    }

下面是来自nodejs服务器端的

function sendMessage(to, title, body) {
    const expo = new Expo();
    let messages = [];

    messages.push({
        to, // Expo user token
        body,
        data: { withSome: 'data' },
        ios: {
            sound: true
        },
        android: {
            "channelId": "chat-messages" //and this
        }
    })
    let chunks = expo.chunkPushNotifications(messages);
    let tickets = [];
    (async () => {
        for (let chunk of chunks) {
            try {
                let ticketChunk = await expo.sendPushNotificationsAsync(chunk);
                tickets.push(...ticketChunk);
            } catch (error) {
                console.error(error);
            }
        }
    })();
}

当用户单击推送通知时,我们还能重定向到网页吗?

1 个答案:

答案 0 :(得分:0)

我在您的后端代码上看到了三个问题(expo push通知文档供参考https://docs.expo.io/versions/latest/guides/push-notifications/):

  1. 根据文档,请求正文上不应有iosandroid属性;
  2. sound应该为'default'或为null,而不是true;
  3. 您在设备上创建了通知频道,但是在发送通知时,您忘记告诉您要发送到哪个频道。

总而言之,您调用expo push notifications api的代码应如下所示:

messages.push({
    to, // Expo user token
    title: 'some title', //it is good practice to send title, and it will look better
    body,
    data: { withSome: 'data' },
    priority: 'high', //to make sure notification is delivered as fast as possible. see documentation for more details
    sound: true, //for iOS devices and android below 8.0
    channelId: 'chat-messages', //for devices on android 8.0 and above
})

我希望这会有所帮助。