Access PNMessageResult in PubNub Swift

与世无争的帅哥 提交于 2019-12-12 12:06:13

问题


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


来源:https://stackoverflow.com/questions/31920108/access-pnmessageresult-in-pubnub-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!