gpt4 book ai didi

iOS:通过 url 请求向 firebase 服务发送推送通知

转载 作者:搜寻专家 更新时间:2023-10-31 19:32:09 25 4
gpt4 key购买 nike

我正在构建一个测试应用程序来发送推送通知,这是我的代码:

static func sendRequestPush(){
let json: [String: Any] = ["to": "key",
"priority": "high",
"notification": ["body":"Hello1", "title":"Hello world","sound":"default"]]
let urlStr:String = "https://fcm.googleapis.com/fcm/send"
let url = URL(string:urlStr)
let jsonData = try? JSONSerialization.data(withJSONObject: json)
var request = URLRequest(url: url!)
request.httpMethod = "POST"
request.httpBody = jsonData
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
print(error?.localizedDescription ?? "No data")

return
}
let responseJSON = try? JSONSerialization.jsonObject(with: data, options: [])
if let responseJSON = responseJSON as? [String: Any] {
print(responseJSON)
}
}

task.resume()
}

问题是我没有收到来自 googleapis 的任何响应,也没有收到推送通知。我从仪表板而不是我的代码收到推送通知。

你们有谁知道我做错了什么吗?

非常感谢您的帮助。

最佳答案

试试下面的代码,它的效果很好:)

 func sendRequestPush()  {
// create the request
let url = URL(string: "https://fcm.googleapis.com/fcm/send")
let request = NSMutableURLRequest(url: url!)
request.httpMethod = "POST"
request.setValue("key=putYourLegacyServerKeyHere", forHTTPHeaderField: "authorization")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
let parameters = ["to": "putYourFCMToken",
"priority": "high",
"notification": ["body":"Hello1", "title":"Hello world","sound":"default"]] as [String : Any]
do {
request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted) // pass dictionary to nsdata object and set it as request body
} catch let error {
print(error.localizedDescription)
}
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
let dataTask = session.dataTask(with: request as URLRequest) { data,response,error in
let httpResponse = response as? HTTPURLResponse
if (error != nil) {
print(error!)
} else {
print(httpResponse!)
}
guard let responseData = data else {
print("Error: did not receive data")
return
}
do {
guard let responseDictionary = try JSONSerialization.jsonObject(with: responseData, options: [])
as? [String: Any] else {
print("error trying to convert data to JSON")
return
}
print("The responseDictionary is: " + responseDictionary.description)
} catch {
print("error trying to convert data to JSON")
return
}
DispatchQueue.main.async {
//Update your UI here
}
}
dataTask.resume()
}

“putYourLegacyServerKeyHere”根据您可以在 FCM 控制台中获得的 key 更改此设置

“putYourFCMToken”使用您在 didReceiveRegistrationToken(FCM 委托(delegate))中获得的 fcm token 更改此

关于iOS:通过 url 请求向 firebase 服务发送推送通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51145543/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com