0

Is it possible to find a push notification from the client using swift? I searched online and the only examples, documentation I found were strictly related to the use of Firebase Cloud Functions and or using the Firebase Console.

I wanted to know if it's possible to create and send a notification using Firebase Cloud Messaging from the client.

StackGU
  • 868
  • 9
  • 22
  • 1
    *firebaser here* Calls to the FCM REST API to send messages require that you specify the FCM *server** key in your code. As its name implies, this key should only be used in server-side code, or in an otherwise trusted environment. The reason for this is that anyone who has the FCM server key can send whatever message they want to all of your users. If you include this key in your iOS app, a malicious user can find it and you'd be putting your users at risk. See https://stackoverflow.com/a/37993724 for a better solution. – Frank van Puffelen Apr 02 '21 at 15:11

1 Answers1

2

It's actually possible using the firebase rest api, the following endpoint could be used to send a notification:

https://fcm.googleapis.com/fcm/send

The HTTP request must be a POST request with these headers:

Authorization: key=<server_key>

Content-Type: application/json

and the following body:

{
  "to" : "<FCM TOKEN>",
  "collapse_key" : "type_a",
  "priority": 10,
  "data" : {
    "body" : "Notification",
    "title": "Notification title"
    }
}

Of course you need to know to the FCM token of the target device that should receive the notification or at least the topic where the device/user is subscribed to. If you want to send notification to a specific topic use the following body:

{
  "to" : "/topics/<YOUR_TOPIC>",
  "collapse_key" : "type_a",
  "priority": 10,
  "data" : {
   "body" : "Notification",
   "title": "Notification title"
   }
}
slimshadystark
  • 107
  • 1
  • 4
  • 1
    Doing this from the client would be a security risk, as you'd have to include the FCM **server** key in the client-side code. Malicious users can then get that key and send any message they want to all of your users. – Frank van Puffelen Apr 02 '21 at 15:10
  • That's true, however this is a way to avoid using Firebase console or Cloud Functions (e.g. on a private VPS) provided that the server key should be protected – slimshadystark Apr 02 '21 at 15:52
  • The FCM API is REST based, so can be called from almost any server. I've recently been looking at PHP implementations, and they solve the security risk equally well (although they wouldn't have the triggering capabilities of Cloud Functions). – Frank van Puffelen Apr 02 '21 at 18:16
  • Would be useful to take a look at this implementation, do you have references? – slimshadystark Apr 03 '21 at 15:05
  • 1
    I was looking at https://github.com/kreait/firebase-php/tree/5.x/src/Firebase/Messaging – Frank van Puffelen Apr 03 '21 at 16:23