Noob
Noob

Reputation: 65

Table View doesn't show data from JSON

My Code:

import UIKit

class HomeVCHome: UIViewController, UITableViewDelegate, UITableViewDataSource {

@IBOutlet weak var usernameLabel: UILabel!
@IBOutlet weak var tableView: UITableView!

var names: [String] = []
var contacts: [String] = []

override func viewDidLoad() {
    super.viewDidLoad()

    self.tableView.delegate = self;
    self.tableView.dataSource = self;

    let url=NSURL(string:"http://mysite/json.aspx")!
    let allContactsData=NSData(contentsOfURL:url)

    var allContacts: AnyObject! = NSJSONSerialization.JSONObjectWithData(allContactsData!, options: NSJSONReadingOptions(0), error: nil)


    if let json = allContacts as? Array<AnyObject> {

        print(json)
        for index in 0...json.count-1 {

            let contact : AnyObject? = json[index]
            print(contact)

            let collection = contact! as Dictionary<String, AnyObject>
            print(collection)

            print(collection["name"])

            let name : AnyObject? = collection["name"]
            let cont : AnyObject? = collection["cont"]

            names.append(name as String)
            contacts.append(cont as String)
        }
    }
    println(names)
    println(contacts)
    tableView.reloadData()
}

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

func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {
    return self.names.count;
}
func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
    println("You selected name : "+names[indexPath.row])
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
    var cell = tableView.dequeueReusableCellWithIdentifier("cell") as? UITableViewCell
     println("ok 1")
    if !(cell != nil) {
        cell = UITableViewCell(style: .Subtitle, reuseIdentifier: "cell")
    }
     println("ok 2")
    cell?.textLabel.text=self.names[indexPath.row]
    cell?.detailTextLabel?.text = self.contacts[indexPath.row]
    println("ok 3")
    return cell!
}

}

i try to run, and i can't see my data in tableView... just blank in table View and i try another code but the same result (table view blank)... what should i do? i don't know its my mistake code or my simulator have problems like that...

Upvotes: 0

Views: 624

Answers (1)

Hrushikesh Betai
Hrushikesh Betai

Reputation: 2217

pls change the method and try:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
     var cell:UITableViewCell = tableView.dequeueReusableCellWithIdentifier(simpleTableIdentifier) as UITableViewCell
     cell.textLabel.text=self.names[indexPath.row]
     cell.detailTextLabel?.text = self.contacts[indexPath.row]
     return cell
}

Upvotes: 1

Related Questions