Ad

FCM UserInfo, How To Drill-down It's Value?

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.
                    }
                }
            }
        }
Ad

Answer

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
    }
Ad
source: stackoverflow.com
Ad