当我收到来自FCM的消息时,我能够打印所有内容,直到点
if let message = userInfo[AnyHashable("message")] {
print(message)
}
消息正文包含类似 => {"sent_at":1521203039,"sender":{"name":"sender_name","id":923},"id":1589,"body":"sdfsadf sdfdfsadf"}
的字符串
类型为"任意">,我希望从此消息对象中读取名称和正文。
func handleNotification(_ userInfo: [AnyHashable: Any]) -> Void {
if let notificationType = userInfo["job_type"] as? String {
if notificationType == "mobilock_plus.message" {
//broadcast message recieved
if let message = userInfo[AnyHashable("message")] {
print(message)
//TODO :- read name and body of message object.
}
}
}
}
我认为您正在查看的是将字符串转换为 Json 对象。
以下答案可以帮助您做到这一点
如何将 JSON 字符串转换为字典?
因此,在@Harsh答案的帮助下,我能够获得如下值。
if let messageString = userInfo[AnyHashable("message")] as? String {
if let dictionaryMessage = UtilityMethods.shared.convertToDictionary(text: messageString) {
if let messageBody = dictionaryMessage["body"] as? String {
if let sender = dictionaryMessage["sender"] as? [String:Any] {
if let senderName = sender["name"] as? String {
}
}
}
}
}
将JSON字符串转换为字典的函数
func convertToDictionary(text: String) -> [String: Any]? {
if let data = text.data(using: .utf8) {
do {
return try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
} catch {
print(error.localizedDescription)
}
}
return nil
}