【问题标题】:Send push notification using Expo使用 Expo 发送推送通知
【发布时间】:2019-11-07 03:20:08
【问题描述】:

我正在尝试使用 Expo 发送推送通知,但我收到了它。但是我的设备上没有振动或声音,也没有弹出。我正在使用带有 Android 9 的 Galaxy S9。我还没有在 Iphone 上尝试过。

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

以下来自expo app

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

当用户点击推送通知时我们也可以重定向到网页吗?

【问题讨论】:

    标签: react-native push-notification expo


    【解决方案1】:

    我发现您的后端代码存在三个问题(expo 推送通知文档供参考https://docs.expo.io/versions/latest/guides/push-notifications/):

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

    话虽如此,调用 expo 推送通知 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
    })
    

    我希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 2018-09-21
      • 1970-01-01
      • 2018-07-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多