How to Parse Data from Socket in Swift?

Muralidharan Kathiresan
Swift India
Published in
Jul 17, 2020

When I was working in a trading app, there is a need to rely on a socket connection to get realtime data. So every time I get data from the socket, need to parse it and feed it into the view to display the data.

Language like JAVA comes with powerful ByteBuffer to make life easier in this case. In iOS, we do not have an exact alternative but we do have options:

  1. Strings in Swift comes with handy default initializers to parse data,

Example:

let unit8: [UInt8] = [67, 97, 102, 195, 169]
let strFromUInt8 = String.init(decoding: unit8, as: UTF8.self)
print(strFromUInt8) // "Cafe\n"let data: Data = Data(unit8)
let stringFromData = String(data: data, encoding: .utf8)
print(stringFromData) // "Optional("Cafe")\n"

This article is updated and moved to my website here 👉🏼 👉 👉🏼

--

--

Muralidharan Kathiresan
Swift India

Crafting beautiful apps to make people’s life easier 😅