Solved

loop through json result in Xcode

Posted on 2015-01-13
1
249 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Yesterday Apple introduced their revolutionary new iOS 5 operating system that claims to be the ultimate mobile technology interface. One of the biggest innovations of the new operating system is the introduction of the iCloud computing network. Thi…
Short answer to this question: there is no effective WiFi manager in iOS devices as seen in Windows WiFi or Macbook OSx WiFi management, but this article will try and provide some amicable solutions to better suite your needs.
Users will learn how resize a batch of photos from a single command in Photoshop via Photoshop's Image Processor. Open up an Image you'd like to resize in Adobe Photoshop: Adjust the image size according to your preferences. Image > Adjustments > …
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…

734 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