0

I'm a total swift novice and even the simplest things I can do. For example, I would like to show in a UItableview a list of names that come from a JSON file, but I am not able to do so.

Specifically, my JSON returns the following:

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

And I have implemented my UITableViewController in the following way:

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

But it does not return anything to me by screen. In fact, if I do a print (centrosList.count) it tells me that zero for five times.

As you can see, I do not have much idea and I sure have more than one fault that I am not able to see. By the way, I'm programming with swift 3

Thanks, any help is appreciated

1 Answer 1

1

It seems that you are not reloading the data to tableView on received it from server.

The general steps to be followed is

  1. set delegate, dataSource for the tableView.

  2. Implement all the required delegate and dataSource methods.

  3. fetch the data from the server and store it to array

  4. reload the tableView.

So, you should add this line below

self.centrosList.append(nombreCentro)

Add this

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

Try and share the results.

1
  • 1
    Excellent! That worked perfectly for my code! You saved my day. Thanks you very much!!
    – Mimmetico
    Commented Jan 15, 2019 at 8:49

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.