title: Extract data from nested JSON in Firebase remoteMessage
body: <p>I am developing a messaging app in swift. I configured firebase cloud messaging and it works, the data arrives to my phone.</p>
  
  <pre><code>func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
      print(remoteMessage.appData)
  }
  </code></pre>
  
  <p>Problem is, I don't know how to extract each value. This is a example of output I receive from the server.</p>
  
  <pre><code>[AnyHashable("message"): {"chat":{"msg":"hey","file":null,"to":"username","date":"2019\/03\/06 08:17:42","group":"TESTING","from":"User Real Name","res":"1"}}, AnyHashable("from"): 123123123]
  </code></pre>
  
  <p>I've tried reading it as a JSON but it doesn't work.</p>
  
  <pre><code>let data = try? JSONSerialization.data(withJSONObject: remoteMessage.appData["message"]
  if let messageJSON = try? JSONSerialization.jsonObject(with: data!) as? [String : Any] {
      print(messageJSON
      if let chatJSON = messageJSON["chat"] as? [String : Any] {
          print(chatJSON)
      }
  }
  </code></pre>
  
  <p>It gives me this error on the first line.</p>
  
  <blockquote>
    <p><strong>* Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*</strong> +[NSJSONSerialziation dataWithJSONObject:options:error:]: Invalid top-level type in JSON write'</p>
  </blockquote>
  
  <p>I followed the suggestions on <a href="https://stackoverflow.com/questions/39883112/how-to-get-the-body-of-a-push-notification-sent-from-firebase-console-in-ios-10">this</a> post, but no luck either.</p>
  
  <pre><code>let d: [String : Any] = remoteMessage.appData["message"] as! [String : Any]
  let body: [String : Any] = d["chat"] as! [String : Any]
  let msg: String = body["msg"] as! String
  print(msg)
  </code></pre>
  
  <blockquote>
    <p>Could not cast value of type '__NSCFString' (0x1e0e52f90) to 'NSDictionary' (0x1e0e53bc0).</p>
  </blockquote>