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

倖福魔咒の 提交于 2019-12-21 13:01:45

问题


Is it possible to send a silent APNs (iOS) remote notification from a Firebase Cloud Function? If so, how can this be done? I want to send data to iOS app instances when the app is not in the foreground, without the user seeing a notification.

I currently send a notification that can be seen by users:

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);
});

I would like to be able to send that id to the app without a visual notification.


回答1:


I figured out how to modify my code to successfully send a silent notification. My problem was that I kept trying to put content_available in the payload, when it really should be in options. This is my new code:

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);
});

I successfully received the silent notification on my iOS device after implementing application:didReceiveRemoteNotification:fetchCompletionHandler and userNotificationCenter:willPresent:withCompletionHandler.




回答2:


If you're talking about APNs notifications, the answer is: No, you can't send a notification without visualisation. You can only disable a sound. But, you can passed an FCM Data message without visualisation. You can read about it here: https://firebase.google.com/docs/cloud-messaging/concept-options

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


来源:https://stackoverflow.com/questions/46058774/can-i-send-a-silent-push-notification-from-a-firebase-cloud-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!