Skip to content

Sending JSON data to stream subscribers

Since iOS SDK build 2.6.36 it is possible to send a message with JSON data from publishing client to all the subscribers of stream published, and receive this message on playing client.

Sending a message

To send a message, WCSStream.sendData() method is used. The message data should be a serialized JSON object

code

@IBAction func sendDataPressed(_ sender: Any) {
    let dataByte = dataToSendTextView.text.data(using: .utf8)
    do {
        let data = try JSONSerialization.jsonObject(with: dataByte!, options: []) as! [String:Any]
        publishStream?.sendData(data)
        dataStatus.text = "Data sent";
        dataStatus.textColor = .green;
    } catch {
        dataStatus.text = "JSON is not valid";
        dataStatus.textColor = .red;

    }
}

Receiving a message

To receive a message, check in onStreamEvent handler: if the event has fpwcsStreamEventTypeData type, then message contains a serialized JSON data

code

playStream?.onStreamEvent({streamEvent in
    if (streamEvent!.type == FPWCSApi2Model.streamEventType(toString: .fpwcsStreamEventTypeData)) {
        let currentDateTime = Date()
        let formatter = DateFormatter()
        formatter.timeStyle = .short
        formatter.dateStyle = .none
        do {
            let jsonData = try JSONSerialization.data(withJSONObject: streamEvent!.payload as Any, options: .prettyPrinted)
            let data = String(data: jsonData, encoding: .utf8) ?? "Fatal data"
            self.dataReceivedTextView.text = self.dataReceivedTextView.text! + formatter.string(from: currentDateTime) + " - " + data + "\n"
        } catch {
        }
    }
})

A message sent from Web SDK or using REST API may be received by this way