MohanSingh MohanSingh - 4 months ago 54
JSON Question

How to extract JSON Data to apply Dynamically in UITableView in swift 2.0?

I'm confused with parsing the data from JSON. Actually, i extracted the whole data. But i confused to apply it to table View rows. so, How to extract JSON Data and Apply it to dynamic tableView rows? lot of thanks in advance.

The JSON Data from URL is given below,

{
"main_result": "1",
"event_listing": [
{
"event_details": "Omega Events",
"pdf_url": "http://portal.shineevents.co.in/portal/assets/uploads/pdf/",
"modified_date": "2016-06-22 14:17:02"
},
{
"event_details": "Cobra Events",
"pdf_url": "http://portal.shineevents.co.in/portal/assets/uploads/pdf/",
"modified_date": "2016-06-22 14:17:18"
},
{
"event_details": "Kovai Events",
"pdf_url": "http://portal.shineevents.co.in/portal/assets/uploads/pdf/",
"modified_date": "2016-06-22 14:23:45"
}
]
}


my whole coding is below, it has my questions clearly in single line comments.

import UIKit

class ViewController: UIViewController, UITableViewDataSource,UITableViewDelegate{

var labels = ["Taylor Swift","Eminem","Avlirl","Michael"] /* i use dummy array now*/

@IBOutlet var tableView: UITableView!


override func viewDidLoad() {
super.viewDidLoad()
retrieveDataFromJASON()
}

func retrieveDataFromJASON()
{
let URL = NSURL(string: "http://portal.shineevents.co.in/portal/api_load/app_load_call")
let requestURL = NSMutableURLRequest(URL: URL!)
requestURL.HTTPMethod = "POST"

let postString = "api=event_list"

requestURL.addValue("123456", forHTTPHeaderField: "X-API-KEY")
requestURL.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)

let task = NSURLSession.sharedSession().dataTaskWithRequest(requestURL) { data, response, error in

guard error == nil && data != nil else {
print("error=\(error)")

return

}

if let httpStatus = response as? NSHTTPURLResponse where httpStatus.statusCode != 200 {

print("statusCode should be 200, but is \(httpStatus.statusCode)")

print("response = \(response)")


}

let responseString2 = try! NSJSONSerialization.JSONObjectWithData(data!, options:.AllowFragments)

print(responseString2) /*prints whole JSON Data*/


let events = responseString2["event_listing"] as? [[String: AnyObject]]

for eventName in events!
{
print(eventName["event_details"])

/* Prints:
Optional(Omega Events)
Optional(Cobra Events)
Optional(Kovai Events) // How to print only First event only
*/

}
}

task.resume()
}

func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return labels.count // How to use event_details.count
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! TableCell
cell.titles.text = labels[indexPath.row] // how to use event_details[indexPath.row]
return cell
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}

Answer

You need to declare instance variable of type [[String: AnyObject]] and use that with UITableViewDelegate method like below

var events : [[String: AnyObject]] = [[String: AnyObject]]()

Now initialize this events object when you get response and after that reload tableView.

self.events = responseString2["event_listing"] as? [[String: AnyObject]]
self.tableView.reloadData()

Now use this events object with UITableView methods

func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return 1
}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return events.count  // How to use event_details.count
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = self.tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! TableCell
    cell.titles.text = events[indexPath.row]["event_details"] as? String 
    return cell
}