user3565259
user3565259

Reputation: 101

Swift - Iterating over nested array of dictionaries

I'm trying to build a personal app for fun using the grace note API for movies playing in theaters near me (JSON format). I'm able to make a call to the server and display what movies are showing. However, I'm trying to display the showtimes, which are embedded deeper in the JSON. I'll try to explain best I can, but the JSON response is:

Theres a root array of x dictionaries (however many movies are in the theater)

Inside each dictionary is a key 'title' which I'm getting and displaying in the table (working correctly).

What I'm getting stuck on is that inside each root dictionary, theres ANOTHER dictionary named 'showtimes'. Inside this dictionary theres x amount of dictionaries (however many times the movie plays in the theater). Inside each of these dictionaries theres a key 'dateTime' which is the actual showtime which I want to get and store into an array for each movie. The idea is to display something like '12:30, 2:45, 5:00,7:30' in the tableview cells detail text label.

Thank you in advance!

Upvotes: 2

Views: 509

Answers (1)

driver733
driver733

Reputation: 402

This will be a helpful resource for you. First of all, let me recommend you to use SwiftyJSON. It will ease up your work with json. Back to your question... (see my comments in code for clarity)

for (index: String, subJson: JSON) in json { // your whole json is an array, "[" in the beginning indicates that
     for (index: String, subSubJson: JSON) in subJson["showtimes"] { // in all "showtime" arrays: 
              self.<YOUR ARRAY>.append(getTime(subSubJson["dateTime"].string!))   // append processed value for key "dateTime" to <YOUR ARRAY>
            }
        }

func getTime(input:String) -> String {
    let dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm"
    let date = dateFormatter.dateFromString(input)
    let calendar = NSCalendar.currentCalendar()
    let comp = calendar.components((.CalendarUnitHour | .CalendarUnitMinute), fromDate: date!)
    let hour = comp.hour
    let minute = comp.minute
    return ("\(hour):\(minute)")
}

This will give you:

10:15
12:20
14:25
16:30
18:35
20:40
10:20
12:30
14:40
16:50
19:0  // not sure why this happens :(

Upvotes: 1

Related Questions