eddy eddy - 6 months ago 14
Swift Question

Using NSJSONSerialization.JSONObjectWithData on dictionaries of varying keys

I'm downloading information from an API that returns data as a Dictionary and converting to an NSDictionary. These dictionaries all have different keys. I have an array of data objects with names that will match these keys, so I wanted to iterate over this array of data objects, pulling out the name of each and passing it in. This doesn't seem to work - only the first name gets passed in. What's the best way to handle this kind of situation? The relevant section of code is below.

for item in itemss {
if let items = json[item.name] as? [[String: AnyObject]] {
for item in items {
if let itemName = lift["name"] as? String {
if let itemStatus = lift["status"] as? String {
if let itemAvail = lift[“avail”] as? Bool {
downloadArray.append(itemStatus)
downloadArray.append(itemAvail)
downloadDict.updateValue(downloadArray, forKey: itemName)
return completionHandler(downloadDict, nil)


The received JSON looks something like this:

{"SomeItem": [{"status": "Closed", "name": "Lower Westside", "avail": "No"}, {"status": "Closed", "name": "Time Table", "avil": "No"}], "AnotherItem": [{"status": "Closed", "name": "Red Lady Connector", "avail": "No"}]}

Answer

If I understand correctly, you're returning/exiting from the code after the first time that you have found all of your keys (hence why only one name added), at line:

return completionHandler(downloadDict, nil)

Perhaps this line could be repositioned after the outer for loop completes, like so:

   for item in itemss {
        if let items = json[item.name] as? [[String: AnyObject]] {
            for item in items {
                if let itemName = lift["name"] as? String {
                    if let itemStatus = lift["status"] as? String {
                        if let itemAvail = lift[“avail”] as? Bool {
                            downloadArray.append(itemStatus)
                            downloadArray.append(itemAvail)
                            downloadDict.updateValue(downloadArray, forKey: itemName)
                            break
                        }
                    }
                }
            }
        }
    }
    return completionHandler(downloadDict, nil)
Comments