0

When I receive message from FCM, I am able to print all it's content till the point

if let message = userInfo[AnyHashable("message")]  {
                        print(message)
                    }

Message body contains string like => {"sent_at":1521203039,"sender":{"name":"sender_name","id":923},"id":1589,"body":"sdfsadf sdfdfsadf"}

Message type is Any, I wish to read name and body from this message object.

func handleNotification(_ userInfo: [AnyHashable: Any]) -> Void {
            if let notificationType = userInfo["job_type"] as? String {
                if notificationType == "mobilock_plus.message" {
                    //broadcast message recieved
                    if let message = userInfo[AnyHashable("message")]  {
                        print(message)
                        //TODO :- read name and body of message object.
                    }
                }
            }
        }
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Sheshnath
  • 3,293
  • 1
  • 32
  • 60
  • you may take help from this https://stackoverflow.com/questions/24013410/how-to-parse-a-json-file-in-swift as the message is `JSON` – swetansh kumar Mar 16 '18 at 12:43

2 Answers2

1

I think what you are looking at is converting a string to Json object.

The following answer can help you do it

How to convert a JSON string to a dictionary?

Harsh
  • 2,852
  • 1
  • 13
  • 27
0

So with the help of @Harsh answer, i was able to get values like below.

if let messageString = userInfo[AnyHashable("message")] as? String {

                    if let dictionaryMessage = UtilityMethods.shared.convertToDictionary(text: messageString) {

                        if let messageBody = dictionaryMessage["body"] as? String {

                            if let sender = dictionaryMessage["sender"] as? [String:Any] {
                                if let senderName = sender["name"] as? String {


                                }
                            }
                        }
                    }

                }

function to convert JSON string into Dictionary

func convertToDictionary(text: String) -> [String: Any]? {
        if let data = text.data(using: .utf8) {
            do {
                return try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
            } catch {
                print(error.localizedDescription)
            }
        }
        return nil
    }
Sheshnath
  • 3,293
  • 1
  • 32
  • 60