我想从设备发送推送通知。
我正在使用此代码:
func sendNotification()
{
var data = [String:Any]()
data["to"] = "a_device_push_token_from_a_real_device"
data["data"] = ["hello": "This is a Firebase Cloud Messaging Device Group Message!"]
data["notification"] = ["title":"test Device","body":"test body","sound":"default"]
let url = URL(string: "https://fcm.googleapis.com/fcm/send")
var request = URLRequest(url: url!)
request.setValue("key=firebase_server_key", forHTTPHeaderField: "Authorization")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
do {
request.httpBody = try JSONSerialization.data(withJSONObject: data, options: .prettyPrinted)
} catch let error {
print(error.localizedDescription)
}
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
print("error=\(error)")
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
}
let responseString = String(data: data, encoding: .utf8)
print("responseString = \(responseString)")
}
task.resume()
}
并且此代码有效,它设法通过" a_device_push_token_from_a_real_device"
向设备发送通知我的问题是:当我拥有用户身份验证ID时,如何获取设备令牌?
我转而使用此代码:
func getNotificationKey(forUserId userId:String)
{
var data = [String:Any]()
data["operation"] = "create"
data["notification_key_name"] = "My Name"
data["registration_ids"] = [userId]
let url = URL(string:"https://android.googleapis.com/gcm/notification")
var request = URLRequest(url: url!)
request.setValue("key=firebase_server_key", forHTTPHeaderField: "Authorization")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("firebase_project_id", forHTTPHeaderField: "project_id")
request.httpMethod = "POST"
do {
request.httpBody = try JSONSerialization.data(withJSONObject: data, options: .prettyPrinted)
} catch let error {
print(error.localizedDescription)
}
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
print("error=\(error)")
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
}
let responseString = String(data: data, encoding: .utf8)
print("responseString = \(responseString)")
}
task.resume()
}
但我收到了:" {\"错误\":\"没有有效的注册ID \"}")但我有一个用户
验证
具有给定ID的表。
有什么建议吗?
我知道firebase云消息令牌之间的区别是什么,注册令牌与this问题不重复。
我问他们之间是否有任何联系?以及如何获取特定注册ID的所有FCM令牌?