I have a link to this JSON that I need to populate cells with the data inside it. It's basically a questions and answers array.
I've tried several solutions on the internet but none seem to adjust to my need.
This is some of the code that I gathered but I don't think it will serve me well.
var preguntas = [String]()
func getPreguntas(url: String, parameters:[String:String]) {
Alamofire.request(url, method: .get, parameters: parameters).responseJSON { response in
if response.result.isSuccess {
print("Success!")
let preguntasJSON: JSON = JSON(response.result.description)
} else {
print("Error \(String(describing: response.result.error))")
}
self.tableView.reloadData()
}
}
func updatePreguntas(json: JSON) {
for (pregunta, respuesta) in json["faqs"] {
let preg = ("\(pregunta) \(respuesta)")
preguntas.append(preg)
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: FAQTableViewCell.reuseIdentifier, for: indexPath)
if let cell = cell as? FAQTableViewCell {
// TODO
cell.preguntaLabel.text = preguntas[indexPath.row]
// cell.respuestaLabel.text = respuestas[indexPath.row]
}
return cell
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return preguntas.count
}
What I need is to have the preguntas
as title of the cells and on tap have the respuestas
show below while expanding the cell. But I've got the expanding part covered. But I can't get those two things from the JSON.
Use Codable
var preguntas = [String]()
Alamofire.request(URL(string:"https://test-tokbox-assistcard.herokuapp.com/faqs")!, method: .get, parameters: [:], encoding: URLEncoding.default, headers: [:]).responseData { response in
if response.result.isSuccess {
guard let data = response.data else { return }
do {
let res = try JSONDecoder().decode(Empty.self, from: data)
print(res.faqs)
preguntas = res.fags.map { $0.pregunta }
}
catch {
print(error)
}
}
self.tableView.reloadData()
}
// MARK: - Empty
struct Empty: Codable {
let faqs: [FAQ]
}
// MARK: - FAQ
struct FAQ: Codable {
let pregunta, respuesta: String
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.