ThisClark ThisClark - 1 year ago 331
Swift Question

Receive JSON object in Swift Socket.IO Client

How can I receive a JSON object in the Swift Socket.IO client?


From on Node.js, I emit a json object as in this simplified example:

socket.emit('welcome', { text : 'Hello, World!' });


In an iOS Swift client, I would like to get this message out of the object.

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

The value of
when I print it out is:

text = "Hello, World!";

When I attempt to parse
with the following (from the Apple Developer Blog)...

let json = try? JSONSerialization.jsonObject(with: data[0], options: [])

...I am met with an error message:

Cannot invoke 'jsonObject' with argument list of type '(with: Any, options: [Any])'

Answer Source

Your data is type of [[String: Any]], get text like below.

if let arr = data as? [[String: Any]] {
    if let txt = arr[0]["text"] as? String {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download