Mahi008 Mahi008 - 8 months ago 48
Swift Question

Swift - How to loop through NSDictionary

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!

Answer

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.