在 Swift Socket.IO 客户端中接收 JSON 对象

Thi*_*ark 2 json socket.io swift swift3

如何在Swift Socket.IO客户端中接收 JSON 对象?

Node.js

从 Node.js 上的 socket.io 中,我发出一个 json 对象,如以下简化示例所示:

socket.emit('welcome', { text : 'Hello, World!' });
Run Code Online (Sandbox Code Playgroud)

迅速

在 iOS Swift 客户端中,我想从对象中获取此消息。

socket?.on("welcome") {[weak self] data, ack in
    print(data)
    if let msg = data[0] as? String {
        print(msg) // never prints; something's wrong
    }
}
Run Code Online (Sandbox Code Playgroud)

data当我打印出来时的值为:

[{
    text = "Hello, World!";
}]
Run Code Online (Sandbox Code Playgroud)

当我尝试data[0]使用以下内容进行解析时(来自Apple 开发者博客)...

let json = try? JSONSerialization.jsonObject(with: data[0], options: [])
Run Code Online (Sandbox Code Playgroud)

...我遇到一条错误消息:

无法使用类型为“(with: Any, options: [Any])”的参数列表调用“jsonObject”

Nir*_*v D 5

您的数据类型为[[String: Any]]text如下所示。

if let arr = data as? [[String: Any]] {
    if let txt = arr[0]["text"] as? String {
        print(txt)
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 是否可以将数据映射到自定义模型,而不是对所有内容进行类型转换并手动添加到模型中? (6认同)