【发布时间】:2019-03-06 10:12:53
【问题描述】:
我正在快速开发一个消息传递应用程序。我配置了 Firebase 云消息传递,它工作正常,数据到达我的手机。
func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
print(remoteMessage.appData)
}
问题是,我不知道如何提取每个值。这是我从服务器收到的输出示例。
[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]
我尝试将它作为 JSON 读取,但它不起作用。
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)
}
}
它在第一行给了我这个错误。
* 由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:“* +[NSJSONSerialzation dataWithJSONObject:options:error:]:JSON 写入中的顶级类型无效”
我遵循了this 帖子上的建议,但也没有运气。
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)
无法将“__NSCFString”(0x1e0e52f90) 类型的值转换为“NSDictionary”(0x1e0e53bc0)。
【问题讨论】:
-
错误信息明确指出键
message的值是字符串而不是字典。在处理 JSON 解码时,永远不要try?。 捕捉错误,它们会帮助你。
标签: json swift firebase google-cloud-messaging firebase-cloud-messaging