fscore
fscore

Reputation: 2619

UITableView creates Blank cells and not any values from JSON

I am trying to load the values from the JSON to the tableview. Here is my code, I dont know what am I missing? It shows me a list of blank cells but not any values.

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    var tableView: UITableView!
    let baseURL = “<url>”
    var items = [UserObject]()

    override func viewDidLoad() {
        super.viewDidLoad()
        let frame:CGRect = CGRect(x: 0, y: 100, width: self.view.frame.width, height: self.view.frame.height-100)
        self.tableView = UITableView(frame: frame)
        self.tableView.dataSource = self
        self.tableView.delegate = self
        self.view.addSubview(self.tableView)

        getJSON()
        dispatch_async(dispatch_get_main_queue(),{
            self.tableView.reloadData()
        })
    }

    //5 rows
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        print("count /(self.items.count)")
        return self.items.count
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCellWithIdentifier("CELL")
        if cell == nil {
            cell = UITableViewCell(style: UITableViewCellStyle.Value1, reuseIdentifier: "CELL")
        }
        let user = self.items[indexPath.row]
        print(self.items)
        cell!.textLabel?.text = user.name
        return cell!
    }


    func getJSON() {
        let url = NSURL(string: baseURL)
        print(url)
        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 results = swiftyJSON.arrayValue
                for entry in results {
                    self.items.append(UserObject(json: entry))
                }
            } else {
                print("error \(error)")
            }
        }

        task.resume()
    }
}

Please note, print("count /(self.items.count)") returns 4 which is correct but

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
//function does not show any print statements.

}

Upvotes: 0

Views: 130

Answers (2)

Kenan Karakecili
Kenan Karakecili

Reputation: 761

You should call the tableview's reloadData func after your async request is finished.

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

var tableView: UITableView!
let baseURL = “<url>”
var items = [UserObject]()

override func viewDidLoad() {
  super.viewDidLoad()
  let frame:CGRect = CGRect(x: 0, y: 100, width: self.view.frame.width, height: self.view.frame.height-100)
  self.tableView = UITableView(frame: frame)
  self.tableView.dataSource = self
  self.tableView.delegate = self
  self.view.addSubview(self.tableView)
  getJSON()
}

//5 rows
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  print("count /(self.items.count)")
  return self.items.count
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
  var cell = tableView.dequeueReusableCellWithIdentifier("CELL")
  if cell == nil {
    cell = UITableViewCell(style: UITableViewCellStyle.Value1, reuseIdentifier: "CELL")
  }
  let user = self.items[indexPath.row]
  print(self.items)
  cell!.textLabel?.text = user.name
  cell!.detailTextLabel?.text = user.date // UPDATE
  return cell!
}


func getJSON() {
  let url = NSURL(string: baseURL)
  print(url)
  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 results = swiftyJSON.arrayValue
      for entry in results {
        self.items.append(UserObject(json: entry))
      }
      dispatch_async(dispatch_get_main_queue(),{
        self.tableView.reloadData()
      })
    } else {
      print("error \(error)")
    }
  }
    task.resume()
  }
}

Upvotes: 2

Ketan Parmar
Ketan Parmar

Reputation: 27438

Your Get json function should be like,

 func getJSON() {
    let url = NSURL(string: baseURL)
    print(url)
    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 results = swiftyJSON.arrayValue
            for entry in results {
                self.items.append(UserObject(json: entry))
            }
            dispatch_async(dispatch_get_main_queue(),{
        self.tableView.reloadData()
    })
        } else {
            print("error \(error)")
        }
    }

    task.resume()
}

and remove

  dispatch_async(dispatch_get_main_queue(),{
        self.tableView.reloadData()
    })

from view didload. I have just put code of reloading table view in completion handler of web service call.

Upvotes: 1

Related Questions