0

I want to send data to my websocket server in swift but the websocket server write function only accepts strings or the data type. Since I did not find any JSON.stringify option for swift I used swiftyJson to create my own type of JSON, but now I need to convert it to data in order to be able to send it to the server.

var json: JSON =  ["name": "Jack", "age": 25]
socket?.send(data: json //<-- This needs to be Data)

I tried wrapping the JSON in Data(json) but this did not work either. Any ideas? I have swiftyJson installed if there is a solution for this.

HangarRash
  • 7,314
  • 5
  • 5
  • 32
Lucas Goldner
  • 617
  • 9
  • 29

2 Answers2

1

The simplest way is a literal

let json =  #"{"name": "Jack", "age": 25}"#
let data = Data(json.utf8)

With SwiftyJSON it's pretty simple, too, but less efficient.

let json: JSON =  ["name": "Jack", "age": 25]
let data = try! json.rawData()
vadian
  • 274,689
  • 30
  • 353
  • 361
1
let data = Data(json.utf8)

By the way, I would not suggest using external libraries for such simple tasks as you become dependent on third-party's works, on which you have no control over. Stick with the foundation model instead.

Luca Sfragara
  • 624
  • 4
  • 16