我有一个类(PushNotificationSender
)。此类包含一个名为 sendPushNotification
的函数,该函数接收 FCM token
、通知标题
和通知正文
。鉴于我知道某个用户的 FCM token
,我已使用它成功向其发送通知。
我的目标:使用此功能向多个用户发送相同的通知。
我尝试为每个用户的 FCM token
调用它,并且还尝试更改函数的参数以获取一组 token ,而不仅仅是一个,但还没有任何效果。关于如何完成升级有什么想法吗?
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()
}
}
最佳答案
要发送到多个 token ,您应该将它们放入 registration_ids
中。
完整文档 here
请不要在代码中共享您的私钥。不安全。
完整代码:
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()
}
}
关于swift - 向多个 FCM token 发送通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60175483/