访问PubNub Swift中的PNMessageResult

时间:2015-08-10 12:52:16

标签: ios swift xcode6 pubnub

See this link

根据以下功能,我可以收到回复,

func client(client: PubNub!, didReceiveMessage message: PNMessageResult!) {
println(message)

但是,我只能将数据作为message.data访问,其格式为PNMessageData。

甚至以下列格式返回数据:

{
message = "{}";
subscribedChannel = 123;
timetoken = 14392105288780634;}

如何在message.data(PNMessageData)中访问消息的值?

2 个答案:

答案 0 :(得分:1)

我编写了简单的方法来解析PNMessageResult

func client(_ client: PubNub, didReceiveMessage message: PNMessageResult) {

    //Message Received on Channel:
    let channel = message.data.channel

    //Message Received:
    guard let messageData = message.data.message as? [String : AnyObject] else { return }

    //Event:
    guard let event:String = messageData["event"] as? String 

    let data:AnyObject = messageData["data"] else { return }

    guard let dict = data as? NSDictionary else { fatalError("Couldn't parse pubnub message") }

    //This will be message in dictionary
    let mutableDict = dict.mutableCopy() as! NSMutableDictionary

}

答案 1 :(得分:0)

您非常接近访问数据。 SDK序列化收到的JSON并将消息存储为 message.data.message 上的字典,该字典应该是字典。

试试这个:

func client(client: PubNub!, didReceiveMessage message: PNMessageResult!) {
    let dictionary: AnyObject = message.data.message
    println(dictionary["accelertiony"]);
    println(dictionary["accelerationx"]);
}