【发布时间】:2021-03-04 00:07:48
【问题描述】:
我只是希望能够向订阅了某个主题的用户发送没有错误的通知。
这是我用来实现这个目标的函数:
func sendNotificationToUser(to topic: String, title: String, body: String) {
let urlString = "https://fcm.googleapis.com/v1/projects/projectname-41f12/messages:send HTTP/1.1"
guard let encodedURLString = urlString.addingPercentEncoding(withAllowedCharacters: .urlFragmentAllowed) else { return }
let url = URL(string: encodedURLString)!
struct PostBody: Codable {
struct Message: Codable {
let topic: String
let notification: [[String: String]]
}
let message: Message
}
let postBody = PostBody(message: PostBody.Message(topic: topic,
notification: [
["title": title],
["body": body]
]))
let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.httpBody = try? encoder.encode(postBody)
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("Bearer ya29.\(self.bearer)", forHTTPHeaderField: "Authorization")
let task = URLSession.shared.dataTask(with: request as URLRequest) { (data, response, error) in
do {
if let jsonData = data {
if let jsonDataDictionary = try JSONSerialization.jsonObject(with: jsonData, options: JSONSerialization.ReadingOptions.allowFragments) as? [String: AnyObject] {
NSLog("Received data:\n\(jsonDataDictionary))")
}
}
} catch let err as NSError {
print(err)
print(postBody.message)
}
}
task.resume()
}
这是我按下按钮后调用它的函数:
getTheSchoolID { (id) in
if let id = id {
self.sendNotificationToUser(to: id, title: "New Event Added!", body: "A new event has been added to the dashboard!!")
}
}
当我按下按钮时,我不断收到一个 NSCocoaError 并且我仍然这样做,所以我做了我的研究并将我的 JSON 通过 jsonlint.com 并通过简单地将括号更改为大括号并在周围添加双引号来验证它对象。现在,当我在 Swift 中运行它时,会出现如下错误:
JSON数据打印在错误中间,我看不到JSON有什么问题,我的http请求有问题吗?
编辑我想要的 JSON 结构:
【问题讨论】:
标签: json swift http-headers firebase-cloud-messaging nsdictionary