【发布时间】:2021-03-03 04:55:01
【问题描述】:
所以我的目标是成功地向订阅了特定主题的用户发送通知,并且没有错误。我有一个用于通过 FCM 发送通知的功能,这里是:
func sendNotificationToUser(to token: String, title: String, body: String) {
getTheSchoolID { (id) in
if let id = id {
let urlString = "https://fcm.googleapis.com/v1/projects/thenameofmyproject-41f12/messages:send HTTP/1.1"
let url = NSURL(string: urlString)!
let paramString: [String: Any] = ["message": ["topic": id,
"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("Bearer \(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.debugDescription)
}
}
task.resume()
}
}
}
我最初从 Youtube 视频中找到了这段代码,并用我的 iPhone 对其进行了测试,它运行良好,但我对其进行了一些修改,使其看起来像这样,现在当这个函数运行时,我收到一个错误,提示 @987654326 @ 正在产生一个 nil 值。
我从文档中复制了格式,只是切换了项目名称,但由于某种原因,我仍然遇到错误。我看不到的网址有问题吗?另外,在我下面显示的图像中,我应该在我的不记名密钥之前添加“ya29.”还是该值很好?
【问题讨论】:
标签: json swift firebase-cloud-messaging google-cloud-messaging httprequest