Solved

loop through json result in Xcode

Posted on 2015-01-13
1
253 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

[Webinar] How Hackers Steal Your Credentials

Do You Know How Hackers Steal Your Credentials? Join us and Skyport Systems to learn how hackers steal your credentials and why Active Directory must be secure to stop them. Thursday, July 13, 2017 10:00 A.M. PDT

Question has a verified solution.

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

Package creation on OS X uses the PackageMaker utility installed as part of the XCode development suite ( on the OSX Client CD).  Packages can be installed as part of the machine build process, or later using Apple Remote Desktop. They are generally‚Ķ
There is a security feature on iOS devices that is nearly impenetrable when it has been activated.  This article will provide some possible solutions as well as necessary steps to take to ensure you do not end up with a locked device.
When you create an app prototype with Adobe XD, you can insert system screens -- sharing or Control Center, for example -- with just a few clicks. This video shows you how. You can take the full course on Experts Exchange at http://bit.ly/XDcourse.
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…

632 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