Brandon Brandon - 6 months ago 11
JSON Question

Getting JSON data to populate a TableView from an Array

I'm able to successfully populate the array with my JSON data inside of the loop, and I'm trying to populate the cells of my TableView with the same information, but currently the list comes up with no content.

import UIKit

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

@IBOutlet weak var table: UITableView!

var headlines = [String]()
let baseURL = "http://api.nytimes.com/svc/topstories/v1/business.json?api-key=123456789"



override func viewDidLoad() {
getJSON()
super.viewDidLoad()
self.table.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
self.table.dataSource = self
self.table.delegate = self
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}


func getJSON() {

let url = NSURL(string: baseURL)
let request = NSURLRequest(URL: url!)
let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration())
let task = session.dataTaskWithRequest(request){ (data, response, error) -> Void in

if error == nil {
let SwiftyJSON = JSON(data: data!)
let theTitle = SwiftyJSON["results"].arrayValue

for title in theTitle{

let titles = title["title"].stringValue
self.headlines.insert(titles, atIndex: 0)
//print("- " + titles)
}

print(self.headlines)

}

else {
print("there was an error")
}
}

task.resume()

}


// From the UITAbleViewDataSource
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return headlines.count
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = self.table.dequeueReusableCellWithIdentifier("cell")! as UITableViewCell
cell.textLabel!.text = self.headlines[indexPath.row]
return cell
}

// From the UITableViewDelegate
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
print("You tapped on cell # \(indexPath.row)")
}
}

Answer

The task is asynchronous, so when you've loaded the array you have to reload your table

func getJSON() {

    let url = NSURL(string: baseURL)
    let request = NSURLRequest(URL: url!)
    let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration())
    let task = session.dataTaskWithRequest(request){ (data, response, error) -> Void in

        if error == nil {
            let SwiftyJSON = JSON(data: data!)
            let theTitle = SwiftyJSON["results"].arrayValue

            for title in theTitle{

                let titles = title["title"].stringValue
                self.headlines.insert(titles, atIndex: 0)
                //print("- " + titles)
            }

            print(self.headlines)
            self.table.reloadData()
        }

        else {
            print("there was an error")
        }
    }

    task.resume()

}
Comments