我正在尝试将来自 api 的请求结果显示到单元格中。我能够发出请求并解析数据。但是当我尝试显示单元格中的内容并打印单元格值时,结果是可选的(“”)。有人能解释一下为什么吗。
cell.restaurantNameLabel.text = apiDataModel.restaurantName
apiDataModel.restaurantName
不是 nil
感谢任何帮助!谢谢
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! DiscoverTableViewCell
cell.discoverImage.image = UIImage(named: "Detail")
cell.restaurantNameLabel.text = apiDataModel.restaurantName
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let currentCell = tableView.cellForRow(at: indexPath) as! DiscoverTableViewCell
print(currentCell.restaurantNameLabel.text)
}
func search(url: String, parameters : [String:String]) {
let headers: HTTPHeaders = ["Authorization":"Bearer \(apiKey)"]
Alamofire.request(url, method: .get, parameters: parameters, headers: headers ) .responseJSON{
URLResponse in
//print(URLResponse)
if URLResponse.result.isSuccess {
let yelpDataJSON = JSON(URLResponse.value!)
self.updateYelpData(Json: yelpDataJSON)
print("\(yelpDataJSON)")
}else{
print("error")
}
}
}
func updateYelpData(Json : JSON){
if let nameJSON = Json["businesses"][0]["name"].string {
apiDataModel.restaurantName = nameJSON
print(apiDataModel.restaurantName)
apiDataModel.restaurantLocation = Json["businesses"][0]["location"]["display_address"][0].stringValue
}else{
print("error")
}
}
最佳答案
您没有向我们展示您在哪里调用了search
,但是request
是一个异步方法,但是您从来没有在您的表上调用过reloadData
在 updateYelpData
中查看。因此, TableView 的初始填充发生在 Alamofire 检索和解析数据之前。
如果在 updateYelpData
中放置一个 tableView.reloadData()
,当 Alamofire 检索到真实数据后, TableView 将更新为真实数据。
关于ios - 为什么 tableviewcell 返回一个可选的 (""),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55667680/