我正在尝试将JSON中的值加载到tableview中。这是我的代码,我不知道我错过了什么?它显示了一个空白单元格列表,但没有显示任何值。
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()
}
}
请注意,print("count /(self.items.count)")
返回4是正确但
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
//function does not show any print statements.
}
答案 0 :(得分:2)
您的异步请求完成后,您应该调用tableview
的{{1}} func。
reloadData
答案 1 :(得分:1)
你的Get json函数应该是,
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()
}
并删除
dispatch_async(dispatch_get_main_queue(),{
self.tableView.reloadData()
})
来自view didload。我刚刚在web service call
的完成处理程序中添加了重新加载表视图的代码。