【问题标题】:Firebase Cloud Messaging to Android works but iOS fails. How to structure payload for iOS?Firebase Cloud Messaging to Android 工作,但 iOS 失败。如何为 iOS 构建有效负载?
【发布时间】:2019-07-16 22:04:26
【问题描述】:

我可以从 Firebase 控制台向我的 iOS 和 Android 应用发送测试通知。因此,我的应用程序设置正确,可以在两个平台上接收推送通知。但是,当我使用云功能发送通知时。仅接收 Android 设备上的通知。 iOS 设备上不显示任何通知。我怀疑这可能与我在云函数中创建有效负载的方式有关。也许我错过了 iOS 的一些东西。如果你能给我一些建议,那就太好了。

我检查了iOS设备的deviceToken是否正确并且正确。

我使用 firebase 控制台向 iOS 设备的同一 deviceToken 发送了一条测试消息,并且通知已发送。

因此,我断定我的问题可能来自我编写的云函数。于是,我分享下云功能:

exports.notifToApp = functions.database.
ref(`/memInfo/{memId}/notifChoice/`).onWrite((snap, context) => {

//send only if exists and new notification OR if doesn't exist
if ((snap.before.exists() && (snap.after.val() !==  snap.before.val())) || !snap.before.exists()) {

//get notification body
const notificationTitle = snap.after.val().memName;
const notificationText = snap.after.val().notifText;

//get and loop over notification subscribers
return admin.database().ref(`/notifics/${context.params.memId}/notifSubs/`).once("value", subs => {
    if (subs.exists()) { 
    return subs.forEach(sub => {

//payload for notification
    const payload = {
        "notification":{
            "title": notificationTitle,
            "body": notificationText,
            "sound": "default",
            "click-action": "FCM_PLUGIN_ACTIVITY",
            "priority": "high"
        }
    }


//deliver notification
return admin.messaging().sendToDevice(sub.val().deviceToken, payload).catch(e => {console.log(e);});

    });
} else { //end: if returned any value
    return 0;
} 
});// end: get and loop over notification subscribers
} else { //end: send only if exists and new notification OR if doesn't exist
    return 0;
}
});

我没有收到任何错误消息。功能成功完成,状态为“OK”。

我使用两台设备进行测试:一台 android 和一台 iOS。两个设备令牌都正确保存在数据库中,以供云功能检索和用于发送消息。

我在运行我的应用的 Android 设备上看到了通知。我希望通知显示在运行相同应用的 iOS 设备上。

从 Firebase 控制台发送的测试消息通知在两台设备上均正确显示。

【问题讨论】:

    标签: ios firebase-cloud-messaging google-cloud-functions


    【解决方案1】:

    我意识到 sendToDevice() 使用了旧版本的有效负载。我在函数中使用了 send() 来使用较新的版本。 (见答案:stackoverflow)

    admin.messaging().send(payload).catch(e => console.log(e));
    

    我根据最新指南更改了有效负载以包含平台特定字段(请参阅firebase docs)

    const payload = {
    "token": sub.val().deviceToken,
    "notification":{"title": notificationTitle,"body": notificationText},
    "android": {"notification": {"sound": "default"}},
    "apns": {"payload": {"aps": {"sound": "default"}}}
    };
    

    现在它可以在两个平台上运行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-08
      • 2021-01-05
      • 2017-08-23
      • 2020-05-03
      • 1970-01-01
      • 2018-09-06
      • 2016-11-21
      • 1970-01-01
      相关资源
      最近更新 更多