我正在构建一个向API发出请求并在表格视图中显示响应的应用程序。我正在使用可解码的。我可以在打印时看到响应。但是我无法将其显示到我的表格视图中。以为我的逻辑是对的。如何显示对表格视图的响应。感谢您的所有答复和解释。
型号
struct Businesses: Decodable {
let businesses : [Business]
}
struct categorie : Decodable{
let title: String
}
struct Business: Decodable {
let name: String
let categories: [categorie]
let rating: Double
let price: String?
}
视图控制器
var businesses = [Business]()
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let business = businesses[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for:
indexPath) as! DiscoverTableViewCell
cell.restaurantNameLabel.text = business.name
cell.restaurantLocationLabel.text = business.name
cell.typeLabel.text = business.name
return cell
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return businesses.count
}
func network (){
let task = session.dataTask(with: request) { (data, response, error) in
if let response = response as? HTTPURLResponse {
print(response)
} else {
print("error")
}
guard let data = data else {return}
// print(String(data: data, encoding: .utf8) ?? "???")
do {
let businessesJSON = try JSONDecoder().decode(Businesses.self, from: data)
self.tableView.reloadData()
print(businessesJSON)
}
} catch {
print("Error parsing JSON: \(error)")
}
}
task.resume()
}
答案 0 :(得分:0)
当您打印businessJSON时,您将获得什么输出?
表视图正在主线程中运行,您应该使用
在主线程中调用tableview.reloadData DispatchQueue.main.async {
self.tableView.reloadData()
}
答案 1 :(得分:0)
在NoSuchElementException
之前添加:self.tableView.reloadData()
示例:
self.businesses = businessesJSON