SWIFT - How to feed a Tableview with information from a Nsarray?

Asked

Viewed 66 times

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

would like to inform on Tableview’s Cell "name" in the textLabel field and "height" as detailLabel

cell.textLabel!.text = nomes[indexPath.row].objectForKey("nome") 

2 answers

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

Then just do

cell.textLabel.text = nomes[indexPath.row].nome

1

The code seems correct. Maybe just force the type, using a cast. Do so:

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

If you make a mistake, make a mistake.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.