i need to send a json string over websocket to get correct response from server. now i created the json and when i try to send it with "socket.write(string: json)" and "socket.write(data: json)" it shows JSON has no member data/string. I am using SwiftyJson to create json.
Yes you can send JSON, binary or any encoding you want over a WebSocket. I assume this is an issue with your implementation, but without a code example of your issue, there isn't much help we can provide.
You can use JSONSerialization to serialize an object into binary JSON data.
func send(_ value: Any, onSuccess: @escaping ()-> Void) {
guard JSONSerialization.isValidJSONObject(value) else {
print("[WEBSOCKET] Value is not a valid JSON object.\n \(value)")
return
}
do {
let data = try JSONSerialization.data(withJSONObject: value, options: [])
socket.write(data: data) {
onSuccess()
}
} catch let error {
print("[WEBSOCKET] Error serializing JSON:\n\(error)")
}
}
Most helpful comment
You can use JSONSerialization to serialize an object into binary JSON data.