0

I am having some problems with sending fcm notifications directly from my SwiftUI app.

When I try to send a notification to token like this, it will work ok:

let request1 = NSMutableURLRequest(url: URL(string: "https://fcm.googleapis.com/fcm/send")!)
    request1.httpMethod = "POST"
    request1.setValue("application/json", forHTTPHeaderField: "Content-Type")
    request1.setValue("\(serverKey)", forHTTPHeaderField: "Authorization")
     
    let json = [
     "to": "my token",
     "notification": [
      "title": "Notification Title",
      "body": "Notification Body"
     ]
    ] as [String : Any]

    let jsonData = try! JSONSerialization.data(withJSONObject: json, options: .prettyPrinted)
    request1.httpBody = jsonData

    URLSession.shared.dataTask(with: request1 as URLRequest) { (data, response, error) in
     if error != nil {
      print(error!)
      return
     }

     print(response!)
    }.resume()

This code works, but when I change the line "to": "my token" into

"topic": "/topics/test_topic"

or

"topic": "test_topic"

It won't send notification to any of the devices subscribed to topic. Devices are connected to topic, because if I send notification to topic from Firebase console, it works OK. Is there any way to send a notification to topic directly from a SwiftUI app?

I would like to be able to send notifications from a SwiftUI app directly, without backend servers.

jnpdx
  • 45,847
  • 6
  • 64
  • 94
misster
  • 11
  • *firebaser here* Calls to the FCM REST API to **send** a message requires 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. By including this key in your iOS app, a malicious user can find it and you're putting your users at risk. See https://stackoverflow.com/a/37993724 for a better solution. – Frank van Puffelen Jan 05 '23 at 14:57
  • Thank you, but none of ways described in the website you linked will work for me. Also, my app will be used by only a small group of trusted people so writing server key inside an app will not be a problem for me. I would like to make it working like this first, maybe later I would migrate to backend server. I suppose there must be a problem with HTTP request, maybe you can see what is wrong and know how to make it work? – misster Jan 05 '23 at 19:55

0 Answers0