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