Solved

loop through json result in Xcode

Posted on 2015-01-13
1
235 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
Comment Utility
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

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
MAC batch file 5 54
Migrating From Parse To Back4App 7 69
iPhone "Documents & Data" overload 13 102
Time Machine backup from iCloud 7 42
The release of the iPhone 6 and the iPhone 6 Plus was extremely successful for Apple. However when iOS 8.1 was introduced, many iPhone users complained of quick battery drainage. Without even knowing, you may be unnecessarily using up your battery p…
In this article we will discuss some EI Capitan Mail app issues and provide some manual process to resolve them.
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 > …
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.

772 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

11 Experts available now in Live!

Get 1:1 Help Now