Cal*_*cki 2 push-notification apple-push-notifications nsjsonserialization swift firebase-cloud-messaging
我有一个班级(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()
}
}
Run Code Online (Sandbox Code Playgroud)
要发送到多个令牌,您应该将它们放入registration_ids. 完整文档在这里
请不要在代码中共享您的私钥。不安全。
完整代码:
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()
}
Run Code Online (Sandbox Code Playgroud)
}
| 归档时间: |
|
| 查看次数: |
7544 次 |
| 最近记录: |