我的问题是:我无法在表格 View 中显示数据。我想显示来自 json 的数据,但我不知道如何获取数据并将其放入一个数组中,然后在 tableview 中显示它
这是代码:
class TableViewControllerNews: UITableViewController {
var Table:NSArray = []
override func viewDidLoad() {
super.viewDidLoad()
CallWebService()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 0
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 0
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell
cell.textLabel?.text = "the cell"
return cell
}
func CallWebService()
{
let UrlApi = "http://www.kaleidosblog.com/tutorial/tutorial.json"
let Url = NSURL(string: UrlApi)
let Session = NSURLSession.sharedSession()
let Work = Session.dataTaskWithURL(Url!, completionHandler: { dataTask, response, error -> Void in
if (error != nil)
{
println(error)
}
var datos:NSData = NSData(data: dataTask)
println(datos)
println(response)
self.ParseoDataToJson(datos)
})
Work.resume()
}
func ParseoDataToJson(datos:NSData)
{
let JsonWithDatos:AnyObject! = NSJSONSerialization.JSONObjectWithData(datos, options: NSJSONReadingOptions.MutableContainers, error: nil)
println(JsonWithDatos)
self.Table = JsonWithDatos as! NSArray
println(self.Table)
println(self.Table.count)
//test
var cell: AnyObject = self.Table[55]
println(cell)
}
最佳答案
您已获取数据并将其放入数组中。只需要像这样将它们加载到 TableView 中:
func ParseoDataToJson(datos:NSData)
{
let JsonWithDatos:AnyObject! = NSJSONSerialization.JSONObjectWithData(datos, options: NSJSONReadingOptions.MutableContainers, error: nil)
println(JsonWithDatos)
self.Table = JsonWithDatos as! NSArray
println(self.Table)
println(self.Table.count)
//test
//var cell: AnyObject = self.Table[55]
//println(cell)
self.tableView.reloadData()
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.Table.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell
let item = self.Table[indexPath.row] as! [String : String]
cell.textLabel?.text = item["country"]
return cell
}
关于ios - Swift:在 TableViewController 中从 Json 加载数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31932029/