How to publish message to a channel using Pubnub Swift in iOS

316 views Asked by At

currently I'm working on an iOS projects where I need to implement WebRTC with Pubnub signaling. I added the PubNubSwift CocoaPods to my project. And when I try to publish a message the publish method expect the message type as JSONCodable. So I created struct as follows,

struct sdpPacket: Codable {
    var type: String?
    var sdp: String?
}

struct sdpDataPacket: Codable {
    var id: String?
    var packet: sdpPacket?
    var number: String?
}

and in the publish method I added these lines,

let sdpPacketVal = sdpPacket(type: "offer", sdp: sdp.description)
let packet = sdpDataPacket(id: uuid, packet: sdpPacketVal, number: self.PubnubChannel)
let jsonData = try! JSONEncoder().encode(packet)
let jsonString = String(data: jsonData, encoding: .utf8)!
print(jsonString)
        
self.appDelegate.pubnub.publish(channel: channelName, message: jsonString) { result in
   print(result.map { "Publish Response at \($0.timetoken.timetokenDate)" })
}

But in the response, I'm getting result as

failure(The request contained a malformed JSON payload)

I will show the jsonString

{
   "id":"userUUID",
   "packet":{
      "type":"offer",
      "sdp":"RTCSessionDescription:\noffer\nv=0\r\no=- 7871361170753072042 2 IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\na=group:BUNDLE audio video\r\na=msid-semantic: WMS RTCmS\r\nm=audio 9 UDP\/TLS\/RTP\/SAVPF 111 103 104 9 102 0 8 106 105 13 110 112 113 126\r\nc=IN IP4 0.0.0.0\r\na=rtcp:9 IN IP4 0.0.0.0\r\na=ice-ufrag:PYqe\r\na=ice-"
   },
   "number":"userPubnubName"
}

I don't know what is the error in my code. Please help me.

1

There are 1 answers

0
Mathew Jenkinson On

It looks like your base encoding the object.

You need is pass in the Swift object.

let sdpPacketVal = sdpPacket(type: "offer", sdp: sdp.description)
let packet = sdpDataPacket(id: uuid, packet: sdpPacketVal, number: self.PubnubChannel)
self.appDelegate.pubnub.publish(channel: channelName, message: jsonString) { result in
   print(result.map { "Publish Response at \($0.timetoken.timetokenDate)" })
}

And then make the two payload objects implement JSONCodable

struct sdpPacket: JSONCodable {
    var type: String?
    var sdp: String?
}
struct sdpDataPacket: JSONCodable {
    var id: String?
    var packet: sdpPacket?
    var number: String?
}