【问题标题】:how to send silent notification / background notification using Firebase Cloud Messaging?如何使用 Firebase Cloud Messaging 发送静默通知/后台通知?
【发布时间】:2020-12-12 03:13:52
【问题描述】:

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

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

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

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

{
   "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)

我尝试发送但出现错误:

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

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

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

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

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

【问题讨论】:

    标签: ios node.js google-cloud-functions firebase-cloud-messaging


    【解决方案1】:

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

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

    要回答您的问题,当您使用带有 Node.js 运行时的 Cloud Function 来使用 sendToDevice(token, payload, options) 方法发送通知时,您需要在函数的选项中传递 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);
    });
    

    【讨论】:

      猜你喜欢
      • 2016-11-03
      • 1970-01-01
      • 2016-11-21
      • 2018-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-14
      • 1970-01-01
      相关资源
      最近更新 更多