У меня есть функция, которая подключается к конечной точке и возвращает результат JSON
, который я сохраняю в массив и использую функцию обратного вызова. Кажется, все настроено правильно. Но данные не отображаются в таблицах при запуске симулятора. Я не уверен, почему? У меня сложилось впечатление, что мне просто нужно запустить tableView.reloadData()
, но это ничего не делает
class ViewConversionsTableViewController: UITableViewController {
/* codesToConvert: The Country code and Country sent from the previous view used to connect to the endpoint
* arraysToDisplay: The total list of countries and their corresponding values to be displayed
*/
var codesToConvert = [String]()
var arraysToDisplay = [String]()
override func viewDidLoad() {
super.viewDidLoad()
calculateRate(value: codesToConvert) {(structuredArray) in
self.arraysToDisplay.append(contentsOf: structuredArray)
}
tableView.reloadData()
}
func calculateRate(value: [String], completionHandler: @escaping (_ structuredArray: [String])->()){
var structuredArray = [String]()
let url = URL(string: "domain.com")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
let postString = "pairs=\(value[0] + value[2])&pairs=\(value[2]+value[0])"
request.httpBody = postString.data(using: String.Encoding.utf8)
let task = URLSession.shared.dataTask(with: request) {(data, response, error) in
do {
var arrayToSend = [String]()
let jsonResult = try JSONSerialization.jsonObject(with: data!)
let results = jsonResult as! [String: Any]
for values in results{
arrayToSend.append(values.key)
arrayToSend.append("\(values.value)")
}
arrayToSend.append(value[1])
arrayToSend.append(value[3])
// Structure the array to the required format
structuredArray.append(arrayToSend[1] + " " + String(arrayToSend[0].prefix(3)))
structuredArray.append(arrayToSend[4])
structuredArray.append(arrayToSend[3])
structuredArray.append(arrayToSend[5] + " · " + String(arrayToSend[2].prefix(3)))
completionHandler(structuredArray)
} catch {
print(error)
}
}
task.resume()
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arraysToDisplay.count
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 100.0
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! ConversionsCell
cell.Amount1.text = arraysToDisplay[0]
cell.currencyName1.text = arraysToDisplay[1]
cell.Amount2.text = arraysToDisplay[2]
cell.currencyName2.text = arraysToDisplay[3]
return cell
}
}