如何在iOS中使用Pubnub Swift将消息发布到频道



目前我正在进行一个iOS项目,需要使用Pubnub信号实现WebRTC。我将PubNubSwift CocoaPods添加到我的项目中。当我尝试发布消息时,发布方法希望消息类型为JSONCodable。所以我创建了如下结构,

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

在发布方法中,我添加了这些行,

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)" })
}

但在回应中,我得到了的结果

failure(The request contained a malformed JSON payload)

我将显示jsonString

{
"id":"userUUID",
"packet":{
"type":"offer",
"sdp":"RTCSessionDescription:noffernv=0rno=- 7871361170753072042 2 IN IP4 127.0.0.1rns=-rnt=0 0rna=group:BUNDLE audio videorna=msid-semantic: WMS RTCmSrnm=audio 9 UDP/TLS/RTP/SAVPF 111 103 104 9 102 0 8 106 105 13 110 112 113 126rnc=IN IP4 0.0.0.0rna=rtcp:9 IN IP4 0.0.0.0rna=ice-ufrag:PYqerna=ice-"
},
"number":"userPubnubName"
}

我不知道我的代码中有什么错误。请帮帮我。

它看起来像是对对象进行编码的基础。

您需要传入Swift对象。

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)" })
}

然后使两个有效载荷对象实现JSONCodable

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

最新更新