简体   繁体   中英

how to populate data in UITableView ? swift

I have managed to retrieve data from JSON using swiftJSON but I am facing problems when i try to populate tableview. I am new to iOS development, so please bear with me on this. I would appreciate if you could help or provide some ideas ?

Here's the code:

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

 func getContactListJSON(){
let urlString = "http://jsonplaceholder.typicode.com/users"
let urlEncodedString = urlString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
let url = NSURL( string: urlEncodedString!)
var task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, innerError) in
    let json = JSON(data: data)
    let contactsArray = json.arrayValue

    dispatch_async(dispatch_get_main_queue(), {
        for contacts in contactsArray
        {
            let id = contacts["id"].stringValue
            let name = contacts["name"].stringValue
            println( "id: \(id) name: \(name)" )
        }
    })
}
task.resume()
}

Here is your complete code for that:

import UIKit

class TableViewController: UITableViewController {

var tableName = [String]()
var tableID = [String]()
override func viewDidLoad() {
    super.viewDidLoad()
    getContactListJSON()

}

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

func getContactListJSON(){
    let urlString = "http://jsonplaceholder.typicode.com/users"
    let urlEncodedString = urlString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
    let url = NSURL( string: urlEncodedString!)
    var task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, innerError) in
        let json = JSON(data: data)
        let contactsArray = json.arrayValue

        dispatch_async(dispatch_get_main_queue(), {
            for contacts in contactsArray
            {
                let id = contacts["id"].stringValue
                let name = contacts["name"].stringValue
                println( "id: \(id) name: \(name)" )
                self.tableName.append(name)
                self.tableID.append(id)
            }
            dispatch_async(dispatch_get_main_queue(),{
                self.tableView.reloadData()
            })
        })
    }
    task.resume()
}

// MARK: - Table view data source

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

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return tableName.count
}


override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! TableViewCell

    // Configure the cell...
    cell.id.text = tableID[indexPath.row]
    cell.name.text = tableName[indexPath.row]
    return cell

    }
}

And HERE is working sample project for you with custom cell.

Here is a piece of code.

var dataArray = [String]()

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

 func getContactListJSON(){
let urlString = "http://jsonplaceholder.typicode.com/users"
let urlEncodedString = urlString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
let url = NSURL( string: urlEncodedString!)
var task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, innerError) in
    let json = JSON(data: data)
    let contactsArray = json.arrayValue

    dispatch_async(dispatch_get_main_queue(), {
        for contacts in contactsArray
        {
            let id = contacts["id"].stringValue
            let name = contacts["name"].stringValue
            println( "id: \(id) name: \(name)" )
            self.dataArray.append(name)
        }
        self.tableView.reloadData()
    })
}
task.resume()
}

Here i am taking name. If you want to display id as well, then create a model class for it.

First declare a local variable NSArray called contactsArray.

    override func viewDidLoad(){
                     super.viewDidLoad()

                     getContactListJSON()


                     }


    //Code for downloading data
     func getContactListJSON(){
                        let urlString = "http://jsonplaceholder.typicode.com/users"
                        let urlEncodedString = urlString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
                        let url = NSURL( string: urlEncodedString!)
                        var task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, innerError) in
                            let json = JSON(data: data)
                            self.contactsArray = json.arrayValue

                            dispatch_async(dispatch_get_main_queue(), {
                                [self.tableView reloadData]
                            })
                        }
                        task.resume()
                        }

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
                    return self.contactsArray.count;
                }

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
                    var cell:UITableViewCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell
                    var contacts:NSDictionary = self.contactsArray[indexPath.row];
                    cell.textLabel?.text =   contacts["name"].stringValue
                    //.......
                    //.......

                    return cell
                }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM