Access PNMessageResult in PubNub Swift

2019-06-24 08:27发布

问题:

See this link

Based on the following function I am able to receive the response,

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

But, I am able to access the data only as message.data which is in the format of PNMessageData.

Even that returns the data in following format:

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

How will I access the value of message inside the message.data(PNMessageData) ?

回答1:

I have written simple method to parse 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

}


回答2:

You are very close to accessing the data. The SDK serializes the JSON being received and stores the message as a dictionary on message.data.message which should be a dictionary.

Try this:

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