我有一堂课(PushNotificationSender
)。此类包含一个名为sendPushNotification
的函数,该函数接收FCM Token
,Notification title
和Notification body
。假设我知道他们的FCM Token
,我就用它成功地向一个用户发送了通知。
我的目标:使用此功能将相同的通知发送给多个用户。
我尝试为每个用户的FCM 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()
}
}
答案 0 :(得分:0)
要发送多个令牌,您应该将它们放入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("key=AAAAUgiuQUM:APA91bFZvhw4nZzZUb32_E_hr3SI1seLNLxHiYGa8yZjwOLUrhSdViK-Sb4bwwveR9bXq-1TR2_xFCNXUoFJajPp6YcKLDGpADoq7BlBmvIU-mGxlH_SjyX3mpZ0jajFzEf0EoiZgd3w", 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()
}
}