用 Swift 填充 JSON 中的表格视图

Fill a tableview from JSON with Swift

我是一个总 swift 新手,即使是最简单的事情我也能做到。例如,我想在 UItableview 中显示来自 JSON 文件的名称列表,但我无法这样做。

具体来说,我的 JSON return 如下:

[{"id_centro":"3","0":"3","nombre":"Colegio Vistarreal","1":"Colegio Vistarreal"},{"id_centro":"1","0":"1","nombre":"IES ITC Sistemas","1":"IES ITC Sistemas"}]

并且我通过以下方式实现了我的 UITableViewController:

import UIKit

class TCentrosController: UITableViewController {

    var centrosList = [String] ()

    override func viewDidLoad() {
        super.viewDidLoad()

        Dologin()

    }


    func Dologin(){

        let url = URL (string: "https://neton.es/WS_neton/lista_centros.php")

        let session = URLSession.shared

        let request = NSMutableURLRequest (url: url!)
        request.httpMethod = "POST"

        let task = session.dataTask(with: request as URLRequest, completionHandler: {

            (data, response, error) in
            guard let _:Data = data else{

                return
            }

            do{

                let json = try JSONSerialization.jsonObject(with: data!, options: []) as! [[String:Any]]

                if json.isEmpty{

                    DispatchQueue.main.async {

                        let alertController = UIAlertController(title: "Atención", message: "No hay centros disponibles", preferredStyle: .alert)


                        let yesAction = UIAlertAction(title: "OK", style: .default)
                        { (action ) -> Void in
                            print("Centros no operativos")
                        }

                        alertController.addAction(yesAction)

                        self.present(alertController, animated: true, completion: nil)

                    }

                    return

                //Si el json no está vacío, sigue por aquí
                }else{

                    let nombreCentro:String = json[1]["nombre"] as! String             
                    self.centrosList.append(nombreCentro)

                }
            }

            catch{
                print("Error")
            }


        })
        task.resume()

    }


  override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return centrosList.count
    }


    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "centros_lista", for: indexPath) as! CeldaCentrosTableViewCell

        cell.labelCell.text = centrosList[indexPath.row]

        return cell
    }
}

但它对我来说 return 没有任何影响。事实上,如果我打印 (centrosList.count),它会告诉我零五次。

正如你所看到的,我没有太多的想法,而且我肯定有不止一个我看不到的错误。顺便说一下,我正在用 swift 3

编程

谢谢,感谢任何帮助

您似乎没有在从服务器接收数据时将数据重新加载到 tableView。

要遵循的一般步骤是

  1. 设置委托,tableView 的数据源。

  2. 实现所有必需的委托和数据源方法。

  3. 从服务器获取数据并将其存储到数组

  4. 重新加载 tableView。

所以,你应该在下面添加这一行

self.centrosList.append(nombreCentro)

添加这个

DispatchQueue.main.async {
  self.tableView.reloadData()
}

尝试并分享结果。