如何使用 Firebase Cloud Messaging 发送静默通知/后台通知?

Agu*_*ana 1 node.js ios google-cloud-functions firebase-cloud-messaging

我需要使用 Firebase Cloud Messaging 在我的 iOS 应用程序中发出静默通知/后台通知,这样即使用户没有点击推送通知,我也可以在应用程序中进行更新。

Apple关于后台通知的文档在这里,据说是

要发送后台通知,请使用 aps 字典创建远程通知,该字典仅包含有效负载中的内容可用键

该文档中的后台通知的示例有效负载如下所示:

{
   "aps" : {
      "content-available" : 1
   },
   "acme1" : "bar",
   "acme2" : 42
}
Run Code Online (Sandbox Code Playgroud)

因此,我在使用云函数节点 JS 发送 FCM 时创建自己的有效负载。我的代码是这样的

        const userToken = device.token

        const payload = {
            data: {
                notificationID : notificationID,
                creatorID : moderatorID,
                creatorName: creatorName,
                title : title,
                body : body,
                createdAt : now,
                imagePath : imagePath,
                type: type
            },
            apps : {
                "content-available" : 1 // to force background data update in iOS 
            }
        }

       await admin.messaging().sendToDevice(userToken,payload)
Run Code Online (Sandbox Code Playgroud)

我尝试发送但出现错误:

'消息有效负载包含无效的“apps”属性。有效属性是“数据”和“通知”。

所以不允许添加“apps”属性,但iOS文档说我需要在有效负载中添加“content-available”。

我在这里读到其他答案,据说有效负载应该这样写

{
"to" : "[token]",
"content_available": true,
"priority": "high",
"data" : {
  "key1" : "abc",
  "key2" : abc
}
Run Code Online (Sandbox Code Playgroud)

但我很困惑如何编写可以在iOS中触发后台通知的有效负载FCM

sll*_*pis 5

根据您收到的错误消息,您应该删除apps属性,因为根据文档,数据通知属性被认为是有效的。

现在,关于您在其他地方找到的有效负载,这是指用于使用 FCM旧版 HTTP API通过 Firebase Cloud Messaging 将消息从应用服务器传递到客户端应用程序的 HTTP 语法。您可以参考文档了解有关新的 HTTP v1 API 的更多信息。

要回答您的问题,当您使用带有 Node.js 运行时的 Cloud Function 来使用sendToDevice(token, Payload, options)方法发送通知时,您需要在函数的options参数中传递contentAvailable

contentAvailable 选项执行以下操作:当发送通知或消息并将其设置为 true 时,将唤醒不活动的客户端应用程序,并且消息将通过 APN 作为静默通知发送,而不是通过 FCM 连接服务器发送。

因此,您的云功能可能如下所示:

const userToken = [YOUR_TOKEN];

const payload = {
  "data": {
    "story_id": "story_12345"
  },
  "notification": {
    "title": "Breaking News" 
  }
}; 

const options = { 
  "contentAvailable": true
};
  

admin.messaging().sendToDevice(userToken, payload, options).then(function(response) { 
console.log('Successfully sent message:', response);
}).catch(function(error) {
console.log('Error sending message:', error);
});
Run Code Online (Sandbox Code Playgroud)