There is a block of JSON data I want to use in a http POST Request for Firebase Cloud Messaging and I will show an image of it down below:
How can I convert this into something that can be encoded in Swift?
I used quicktype.io to see if I can convert it to a data struct in Swift and this is what I got:
How can I implement this in my function?
func sendNotificationToUser(to topic: String, title: String, body: String) {
let urlString = "https://fcm.googleapis.com/v1/projects/nameofproject-41f12/messages:send HTTP/1.1"
guard let encodedURLString = urlString.addingPercentEncoding(withAllowedCharacters: .urlFragmentAllowed) else { return }
let url = URL(string: encodedURLString)!
//This was an old data struct I used but didn't work
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"
do {
request.httpBody = try encoder.encode(postBody)
} catch let err as NSError {
print(request.httpBody)
print(err)
}
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()
}