Caleb Rudnicki
Caleb Rudnicki

Reputation: 395

Send Notification to Multiple FCM Tokens

I have a class (PushNotificationSender). This class holds one function called sendPushNotification which takes in an FCM Token, Notification title, and Notification body. I have used it to successfully send a notification to one user, given that I know their FCM Token.

My goal: to use this function to send the same notification to multiple users.

I have tried to call it for every user's FCM Token and I have also tried to change the function's parameters to get an array of tokens, rather than just one, but nothing has worked yet. Any ideas on how to accomplish upgrade?

PushNotificationSender:

class PushNotificationSender {

    init() {}

    // MARK: Public Functions

    public func sendPushNotification(to token: String, title: String, body: String, completion: @escaping () -> Void) {
        let urlString = "https://fcm.googleapis.com/fcm/send"
        let url = NSURL(string: urlString)!
        let paramString: [String : Any] = ["to" : token,
                                           "notification" : ["title" : title, "body" : body],
                                           "data" : ["user" : "test_id"]
        ]

        let request = NSMutableURLRequest(url: url as URL)
        request.httpMethod = "POST"
        request.httpBody = try? JSONSerialization.data(withJSONObject:paramString, options: [.prettyPrinted])
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        request.setValue(//key, forHTTPHeaderField: "Authorization")
        let task =  URLSession.shared.dataTask(with: request as URLRequest)  { (data, response, error) in
            do {
                if let jsonData = data {
                    if let jsonDataDict  = try JSONSerialization.jsonObject(with: jsonData, options: JSONSerialization.ReadingOptions.allowFragments) as? [String: AnyObject] {
                        NSLog("Received data:\n\(jsonDataDict))")
                    }
                }
            } catch let err as NSError {
                print(err.debugDescription)
            }
        }
        task.resume()
        completion()
    }

}

Upvotes: 2

Views: 8686

Answers (1)

nullx
nullx

Reputation: 188

To send to multiple tokens you should get them into registration_ids. Full documentation here

And PLEASE, don't share your private keys in your code. Is not safe.

Full code:

class PushNotificationSender {

init() {}

// MARK: Public Functions

public func sendPushNotification(to token: String, title: String, body: String, completion: @escaping () -> Void) {
    let urlString = "https://fcm.googleapis.com/fcm/send"
    let url = NSURL(string: urlString)!
    let paramString: [String : Any] = ["registration_ids" : ["<token1>", "<token2>", "<token3>"],
                                       "notification" : ["title" : title, "body" : body],
                                       "data" : ["user" : "test_id"]
    ]

    let request = NSMutableURLRequest(url: url as URL)
    request.httpMethod = "POST"
    request.httpBody = try? JSONSerialization.data(withJSONObject:paramString, options: [.prettyPrinted])
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")
    request.setValue("your key", forHTTPHeaderField: "Authorization")
    let task =  URLSession.shared.dataTask(with: request as URLRequest)  { (data, response, error) in
        do {
            if let jsonData = data {
                if let jsonDataDict  = try JSONSerialization.jsonObject(with: jsonData, options: JSONSerialization.ReadingOptions.allowFragments) as? [String: AnyObject] {
                    NSLog("Received data:\n\(jsonDataDict))")
                }
            }
        } catch let err as NSError {
            print(err.debugDescription)
        }
    }
    task.resume()
    completion()
}

}

Upvotes: 5

Related Questions