Swift - How to loop through NSDictionary

42,559

Solution 1

Here is how you can process a given JSON:

let dataArray = result["data"] as NSArray;

print("Data items count: \(dataArray.count)")

for item in dataArray { // loop through data items
    let obj = item as NSDictionary
    for (key, value) in obj {
        print("Property: \"\(key as String)\"")
    }
}

Remarks:

Remember that you receive parsed objects as NSDictionary and when you iterate through the dictionary, order in which you receive properties may differ from the order in the original JSON.

Solution 2

Check this piece of code for reference:

// MARK: - Firebase
func retrieveData(){
    ref.observe(FIRDataEventType.value, with: { (snapshot) in
        let postDict = snapshot.value as! [String : AnyObject]
        let contactList = postDict["contacts"]!
        let user = FIRAuth.auth()!.currentUser

        let contactArray = contactList[user!.uid]! as! NSDictionary

        for (key,_) in contactArray {

            let contact:NSObject = contactArray[key] as! NSObject
            let firstName:String! = contact.value(forKey: "firstName") as? String
            let lastName:String! = contact.value(forKey: "lastName") as? String
            let company:String! = contact.value(forKey: "company") as? String
            let phone:String! = contact.value(forKey: "phone") as? String
            let email:String! = contact.value(forKey: "email") as? String

            print(contact.value(forKey: "firstName")!)
            contacts.append(Contact(firstName:firstName, lastName: lastName, company: company, phone: phone, email: email))
        }
        self.tableView.reloadData()

    })

}

It specially gets tricky when you parse the key value into the usable object that is where the NSObject comes to rescue so that you can get the values for key.

Share:
42,559
Mahi008
Author by

Mahi008

Updated on July 20, 2022

Comments

  • Mahi008
    Mahi008 almost 2 years

    Hi I'm currently learning Swift, and I wanted to extract data from a JSON Api, My Swift code looks like this. To be specific, I need to extract each and every key and its value,(for example: print the value of title, cover etc..)

    //Json request
    var error: NSError?
    var raw = NSString.stringWithString("http://example.com/MovieAPI/api/v1/movies/")
    var api_url = NSURL.URLWithString(raw)
    let jsonData: NSData = NSData.dataWithContentsOfURL(api_url, options: nil, error: &error)
    let result = NSJSONSerialization.JSONObjectWithData(jsonData, options: nil, error: &error)
    as NSDictionary
    for val in result {
       for (var i=0; i < val.value.count; i++){
           //println(val.value.valueAtIndex(3)) Not Working
       }
    }
    

    and the structure of my JSON is

    {
      data: [
          {
            id: 2,
            title: "Hunger Games",
            cover: "http://example.com",
            genre: 2
           }
      ]
    }
    

    Help!