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

how to send silent notification / background notification using Firebase Cloud Messaging?

我需要使用 Firebase 云消息传递在我的 iOS 应用程序中发出静默 notification/background 通知,这样即使用户没有点击推送通知我也可以在应用程序中进行更新。

苹果关于后台通知的文档在here,据说

To send a background notification, create a remote notification with an aps dictionary that includes only the content-available key in the payload

来自该文档的后台通知的示例负载如下:

{
   "aps" : {
      "content-available" : 1
   },
   "acme1" : "bar",
   "acme2" : 42
}

所以我在使用云函数节点 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)

我尝试发送但出现错误:

'Messaging payload contains an invalid "apps" property. Valid properties are "data" and "notification".

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

看了里的其他回答,据说payload应该这样写

{
"to" : "[token]",
"content_available": true,
"priority": "high",
"data" : {
  "key1" : "abc",
  "key2" : abc
}

但是我很困惑如何在iOS

中编写可以触发后台通知的payload FCM

根据您收到的错误消息,您应该删除 apps 属性,因为 datanotification 属性被认为是有效的,根据 documentation.

现在,关于您在其他地方找到的负载,这是指用于通过 Firebase 云消息传递将消息从您的应用服务器传递到客户端应用的 HTTP 语法,使用 FCM legacy HTTP API. You can refer to the the documentation 了解更多信息新的 HTTP v1 API.

为了回答您的问题,当您使用带有 Node.js 运行时的 Cloud Functions 时,使用函数的 options 参数中的 sendToDevice(token, payload, options) method, you will need to pass the contentAvailable 发送通知。

contentAvailable 选项执行以下操作:当发送通知或消息并将其设置为 true 时,不活动的客户端应用程序将被唤醒,消息通过 APNs 作为静默通知发送,并且不通过 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);
});