如何在UITableView中填充数据?迅速

时间:2015-05-11 09:16:44

标签: ios uitableview swift swifty-json

我已经设法使用swiftJSON从JSON检索数据但是当我尝试填充tableview时我遇到了问题。我是iOS开发的新手,所以请耐心等待。如果您能提供帮助或提供一些想法,我将不胜感激?

以下是代码:

 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()
}

3 个答案:

答案 0 :(得分:8)

以下是您的完整代码:

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

    }
}

HERE正在为自定义单元格提供样本项目。

答案 1 :(得分:0)

这是一段代码。

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()
}

我在这里取名。如果你想显示id,那么为它创建一个模型类。

答案 2 :(得分:0)

首先声明一个名为contactsArray的局部变量NSArray。

    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
                }