Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 257
  • Last Modified:

loop through json result in Xcode

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
jellydeal
Asked:
jellydeal
1 Solution
 
Shahan AyyubSenior Software Engineer - iOSCommented:
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

Important Lessons on Recovering from Petya

In their most recent webinar, Skyport Systems explores ways to isolate and protect critical databases to keep the core of your company safe from harm.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now