我正在尝试使用外部数据库中的一些数据加载UItable。我能够在输出面板中打印所需的数据,但无法获取tableview上的数据。我怎样才能解决这个问题?
代码:
import UIKit
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
//let myarray = ["item1", "item2", "item3"]
var group = [Group]()
@IBOutlet weak var tableview: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
let url = URL(string: "http://www.myurl/myfile.php")
let task = URLSession.shared.dataTask(with: url! as URL) { data, response, error in
guard let data = data, error == nil else { return }
print(NSString(data: data, encoding: String.Encoding.utf8.rawValue))
}
task.resume()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
tableview.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
//return myarray.count
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "groupCell", for: indexPath) as! UITableViewCell
// cell.textLabel?.text = myarray[indexPath.item]
return cell
}
}
答案 0 :(得分:0)
Tableview在接收数据之前重新加载。完成任务后需要重新加载表视图。
let task = URLSession.shared.dataTask(with: url! as URL) { data, response, error in
guard let data = data, error == nil else { return }
print(NSString(data: data, encoding: String.Encoding.utf8.rawValue))
//Store into your array depend on response.
DispatchQueue.main.async() {
self.tableView.reloadData()
} } task.resume()