Search code examples
iosjsonswiftnsdictionary

Swift - Accessing JSON value held within an NSDictionary


Please see the picture attached. I am creating an iOS app with a Laravel API as the back-end. Upon registration, before the user receives a message that their account has successfully been created, I am checking to make sure that the 'id' field exists. I can see this value being saved in mySQL database, and it is being returned in the parseJSON variable which is an NSDictionary. However, parseJSON["id"] returns null. How can I access just the 'id' value, so that the userId variable is set to 35 in the example below?

I've looked at some documentation online of NSDictionaries and other questions/answers but haven't been able to fix this issue.

enter image description here


Solution

  • You need to first parse the higher level at message and then the value of message dict. Try like below,

     if let message = parseJSON["message"] as? [String: Any], let identifier = message["id"] as? Int {
        // Print Identifier
     }