Reputation: 862
The following function is used to send a notification to a user. How to send a notification to a multiple user at once?
func sendPushNotification(to token: String, title: String, body: String) {
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=SERVER-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()
}
Upvotes: 1
Views: 260
Reputation: 7213
You can send push notification to multiple users by adding multiple tokens.
Here receiverToken is multiple user's FCM tokens.
class func sendMultiple(title:String,message:String,receiverToken : [String]) -> ()
{
var postParams : [String : Any] = [:]
postParams = ["registration_ids":receiverToken,
"notification":[
"title":title,
"sound":"default",
"body":message],
"data":[
],
"apns":[
"headers":[
"apns-priority":"10"],
"payload":[
"headers":[
"category":"NEW_MESSAGE_CATEGORY"]]]
]
print(postParams)
var request = URLRequest(url: URL.init(string: "https://fcm.googleapis.com/fcm/send")!)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue(String(format:"key=%@", "YOUR_SERVER_KEY"), forHTTPHeaderField: "Authorization")
request.httpBody = try! JSONSerialization.data(withJSONObject: postParams, options: [])
URLSession.shared.dataTask(with: request, completionHandler:
{ (responseData, response, responseError) -> Void in
}).resume();
}
Please make sure to replace the "YOUR_SERVER_KEY" with your sever key
Upvotes: 1