在使用Web套接字时,从Web服务获取响应时,类型“Any”没有下标成员

时间:2017-11-30 11:09:11

标签: ios json swift3 websocket

我已经尝试使用Dictionary代替Any但我没有找到所需的值
我想从以下代码

中的文本值中仅打印“msg”值
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

            }
        }

2 个答案:

答案 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()
}