ThisClark ThisClark - 1 month ago 66
Swift Question

Receive JSON object in Swift Socket.IO Client

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

Node.js

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

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


Swift

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

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


The value of
data
when I print it out is:

[{
text = "Hello, World!";
}]


When I attempt to parse
data[0]
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

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 {
        print(txt)
    }
}