以下函数用于向用户发送通知。如何一次向多个用户发送通知?
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()
}
答案 0 :(得分:1)
您可以通过添加多个令牌向多个用户发送推送通知。
这里的receiverToken是多个用户的FCM令牌。
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();
}
请确保将“YOUR_SERVER_KEY”替换为您的服务器密钥