我可以从 Firebase 云函数发送静默推送通知吗?

Can I send a silent push notification from a Firebase cloud function?

是否可以从 Firebase Cloud Function 发送静默 APNs (iOS) 远程通知?如果是这样,如何做到这一点?当应用程序不在前台时,我想将数据发送到 iOS 个应用程序实例,而用户不会看到通知。

我目前发送的通知可以被用户看到:

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

exports.sendNotifications = functions.database.ref('/events/{pushId}').onWrite(event => {
  const id = event.params.pushId

  const payload = {
    notification: {
      title: 'An event has occurred!',
      body: 'Please respond to this event.',
      event_id: id
    }
  };

  return admin.messaging().sendToTopic("events", payload);
});

我希望能够在没有视觉通知的情况下将 id 发送到应用程序。

如果您谈论的是 APNs 通知,答案是:不,您不能在没有可视化的情况下发送通知。您只能禁用声音。但是,您可以在不可视化的情况下传递 FCM 数据消息。您可以在这里阅读:https://firebase.google.com/docs/cloud-messaging/concept-options

 {  
   "to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
   "data" : {
     "Nick" : "Mario",
     "body" : "great match!",
     "Room" : "PortugalVSDenmark"
   }
}

我想出了如何修改我的代码以成功发送静默通知。我的问题是我一直试图将 content_available 放在 payload 中,而实际上它应该放在 options 中。这是我的新代码:

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

exports.sendNotifications = functions.database.ref('/events/{pushId}').onWrite(event => {
  const id = event.params.pushId

  const payload = {
    data: {
      title: 'An event has occurred!',
      body: 'Please respond to this event.',
      event_id: id
    }
  };

  const options = {
    content_available: true
  }

  return admin.messaging().sendToTopic("events", payload, options);
});

在实施 application:didReceiveRemoteNotification:fetchCompletionHandleruserNotificationCenter:willPresent:withCompletionHandler 后,我在 iOS 设备上成功收到了静默通知。