I am developing a messaging app in swift. I configured firebase cloud messaging and it works, the data arrives to my phone.
func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
print(remoteMessage.appData)
}
Problem is, I don't know how to extract each value. This is a example of output I receive from the server.
[AnyHashable("message"): {"chat":{"msg":"hey","file":null,"to":"username","date":"2019\/03\/06 08:17:42","group":"TESTING","from":"User Real Name","res":"1"}}, AnyHashable("from"): 123123123]
I've tried reading it as a JSON but it doesn't work.
let data = try? JSONSerialization.data(withJSONObject: remoteMessage.appData["message"]
if let messageJSON = try? JSONSerialization.jsonObject(with: data!) as? [String : Any] {
print(messageJSON
if let chatJSON = messageJSON["chat"] as? [String : Any] {
print(chatJSON)
}
}
It gives me this error on the first line.
* Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '* +[NSJSONSerialziation dataWithJSONObject:options:error:]: Invalid top-level type in JSON write'
I followed the suggestions on this post, but no luck either.
let d: [String : Any] = remoteMessage.appData["message"] as! [String : Any]
let body: [String : Any] = d["chat"] as! [String : Any]
let msg: String = body["msg"] as! String
print(msg)
Could not cast value of type '__NSCFString' (0x1e0e52f90) to 'NSDictionary' (0x1e0e53bc0).
You need
do {
let d = remoteMessage.appData["message"] as! String
let res = try JSONDecoder().decode(Root.self,from:Data(d.utf8))
print(res)
}
catch {
print(error)
}
struct Root: Codable {
let chat: Chat
}
struct Chat: Codable {
let msg: String
let file: String?
let to, date, group, from: String
let res: String
}
as message
key contains a json String not a dictionary
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.