我已经尝试使用Dictionary代替Any但我没有找到所需的值
我想从以下代码
webSocket.event.message = { message in
if let text = message as? Any {
print("recv: \(text)")//recv: {"status":"200","msg":"successful"}
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm"
var time = dateFormatter.string(from: Date())
self.messagesReceived["messageReceived"] = text["msg"]
self.messagesReceived["time"] = time
self.messagesDetails["received"] = self.messagesReceived
}
}
答案 0 :(得分:0)
看起来您正在从服务器获取字符串消息。
webSocket.event.message = { message in
if let text = message as? String, let responseData = let data = text.data(using: .utf8) {
do {
let responseDict = try JSONSerialization.jsonObject(with: responseData, options: []) as? [String: Any]
//Your code
} catch {
print(error.localizedDescription)
}
}
}
答案 1 :(得分:0)
webSocket.event.message = { message in
if let data = (message as! String).data(using: .utf8) {
do {
let text = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm"
let time = dateFormatter.string(from: Date())
self.messagesReceived["messageReceived"] = text!["msg"] as? String
self.messagesReceived["time"] = time
self.messagesDetails["received"] = self.messagesReceived
} catch {
print(error.localizedDescription)
}
}
}
messagesDisplay.append(messagesDetails)
tableView.reloadData()
}