Solved

loop through json result in Xcode

Posted on 2015-01-13
1
238 Views
Last Modified: 2015-02-12
Hi,
I have some working code the reads two JSON values and displays them:
class ViewController: UIViewController {
  @IBOutlet weak var dateLabel: UILabel!
  @IBOutlet weak var timeLabel: UILabel!
  
  override func viewDidLoad() {
    super.viewDidLoad()
    
    // 1
    let urlAsString = "http://date.jsontest.com"
    let url = NSURL(string: urlAsString)!
    let urlSession = NSURLSession.sharedSession()
    
    //2
    let jsonQuery = urlSession.dataTaskWithURL(url, completionHandler: { data, response, error -> Void in
      if (error != nil) {
        println(error.localizedDescription)
      }
      var err: NSError?
      
      // 3
      var jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as NSDictionary
      if (err != nil) {
        println("JSON Error \(err!.localizedDescription)")
      }
      
      // 4
      let jsonDate: String! = jsonResult["date"] as NSString
      let jsonTime: String! = jsonResult["time"] as NSString
      
      dispatch_async(dispatch_get_main_queue(), {
        self.dateLabel.text = jsonDate
        self.timeLabel.text = jsonTime
      })
    })
    // 5
    jsonQuery.resume()
  }

Open in new window


The JSON it uses is :
{
   "time": "08:05:21 AM",
   "date": "01-13-2015"
}

Open in new window


I need to modify the code to loop through an array and don't know how, heres the JSON I need to loop through:

Open in new window

[
{
   "time": "08:05:21 AM",
   "date": "01-13-2015"
},
{
   "time": "07:05:19 AM",
   "date": "01-13-2015"
},
{
   "time": "06:05:00 AM",
   "date": "01-13-2015"
},
]
the sample code only expects a flat JSON response, I need to loop through the array ..
Any help appreciated,
thanks
0
Comment
Question by:jellydeal
1 Comment
 
LVL 19

Accepted Solution

by:
Shahan Ayyub earned 500 total points
ID: 40547646
I would like to add some pointers in your code, but unfortunately i do not have swift setup right now. But will try my best to do what is possible:

This part:

    // 4
      let jsonDate: String! = jsonResult["date"] as NSString
      let jsonTime: String! = jsonResult["time"] as NSString
      
      dispatch_async(dispatch_get_main_queue(), {
        self.dateLabel.text = jsonDate
        self.timeLabel.text = jsonTime
      })

Open in new window


requires modification something like:

// Here `start` should be zero to access first element of json array
// Here `end`  should be (number of elements in array - 1), may be `count` property can help you.
for i in start..<end     
 {
     // 4
     //  let jsonDate: String! = jsonResult["date"] as NSString
     // let jsonTime: String! = jsonResult["time"] as NSString
     // Here access values like
     // jsonResult[i]["date"]       
     // jsonResult[i]["time"]      
     // Save this value in your modal objects or in array, dictionary etc
     // So you may use it to show in controls e.g., UITableView

      // Here once you are done dealing with parsing the datasource transfer control to the main thread
      // So it would be able to display relevant result sets.
      dispatch_async(dispatch_get_main_queue(), {
        //self.dateLabel.text = jsonDate
        //self.timeLabel.text = jsonTime
        // If you have one label for date and time then select the appropriate from the above parsed datasource
        // e.g.,  self.dateLabel.text = yourParsedArray[0]["date"]; // assume you save it like "array of dictionary"
        //e.g.,   yourParsedArray[0] = new dictionary ("date", "13-01-2015", "time", "00:00:00");
      })
 }

Open in new window


May be this guideline could help you.
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

The Basics of Storyboard Storyboards were first introduced to developers in the release of iOS 5. They save the developer the trouble of designing each screen’s interface in a different file. The storyboard allows you to see the conceptual mockup o…
A lot of new and distinct gadgets are making their appearance every other day. The latest gadget that has wooed the attention of all gadget lovers and non gadget lovers alike is the Smartwatch. This tiny gadget is capable of offering live access to …
This Micro Tutorial hows how you can integrate  Mac OSX to a Windows Active Directory Domain. Apple has made it easy to allow users to bind their macs to a windows domain with relative ease. The following video show how to bind OSX Mavericks to …
CodeTwo Sync for iCloud (http://www.codetwo.com/sync-for-icloud?sts=6554) automatically synchronizes your Outlook 2016, 2013, 2010 or 2007 folders with iCloud folders available via iCloud Control Panel. This lets you automatically sync them with…

910 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now