1

目前我正在开发一个需要使用 Pubnub 信号实现 WebRTC 的 iOS 项目。我将 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:\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"
}

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

4

1 回答 1

2

看起来您的基本编码对象。

您需要传入 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)" })
}

然后让这两个payload对象实现JSONCodable

struct sdpPacket: JSONCodable {
    var type: String?
    var sdp: String?
}
struct sdpDataPacket: JSONCodable {
    var id: String?
    var packet: sdpPacket?
    var number: String?
}
于 2020-09-24T17:00:19.277 回答