SWIFT - How to feed a TableView with information from an NSArray?

2
var nomes:NSArray = []    
override func viewDidLoad() {
super.viewDidLoad()    

      Alamofire.request(.GET, MyUrl,parameters: nil,encoding: .JSON).response { (_, _, data, error) in    
      self.nomes = try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions()) as! NSArray
        print(self.nomes)
  }    
}

And I'm getting this information:

[{"nome":"marcos","idade":"23","altura":"1.83"},
{"nome":"ivan","idade":"25","altura":"1.89"},
{"nome":"pedro","idade":"21","altura":"1.78"}]

I would like to inform on the cell of the TableView "name" in the textLabel field and "height" as detailLabel

cell.textLabel!.text = nomes[indexPath.row].objectForKey("nome") 
    
asked by anonymous 07.08.2016 / 04:00

2 answers

1

The code seems correct. Maybe you just need to force the guy, using a cast. Here's how:

var temp: NSString = nomes[indexPath.row].objectForKey("nome") as NSString
cell.textlabe.text = temp

If you make a mistake, post the error.

    
09.08.2016 / 21:50
1

A better solution would be to declare a struct with these attributes

struct Pessoa: Codable {
    var nome: String
    var idade: Int
    var altura: Double
}

And using JSONDecoder

var nomes: [Pessoa]
Alamofire.request(.GET, MyUrl,parameters: nil,encoding: .JSON).response {
    (_, _, data, error) in    
    self.nomes = try jsonDecoder.decode([Pessoa.self], from: data)
    print(self.nomes)
}

That's all there is to it.

cell.textLabel.text = nomes[indexPath.row].nome
    
03.10.2018 / 20:42