我试图从Firebase中检索数据并将其显示在表视图中。问题是这些值没有显示在表视图中。
到目前为止,我正在遍历firebase中的数据,并将每个字典存储在一个数组中。然后使用这个字典数组,我尝试在表视图单元格中设置一个标签,该标签等于字典中的一个值。
这是我的代码:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let arrayWithFirbaseInfo : Array<Dictionary<String, Any>> = findCordinateFolder()
print(arrayWithFirbaseInfo)
let cell = tableView.dequeueReusableCell(withIdentifier: "customTableCell", for: indexPath) as! NearbyTableViewCell
cell.distanceLabel.text = arrayWithFirbaseInfo.filter({$0["favorite drink"] != nil}).map({$0["favorite drink"]!}) as? String
return cell
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 3
}
func findCordinateFolder() -> Array<Dictionary<String, Any>>{
var firebaseArray = Array<Dictionary<String, Any>>()
ref = Database.database().reference()
var currentLocation: CLLocation!
currentLocation = locManager.location
GeocodeFunction().geocode(latitude: currentLocation.coordinate.latitude, longitude: currentLocation.coordinate.longitude, completion: { placemark, error in
if let error = error as? CLError {
print("CLError:", error)
return
} else if let placemark = placemark?.first {
// you should always update your UI in the main thread
DispatchQueue.main.async {
// update UI here
// let city = placemark.locality ?? "unknown"
let state = placemark.administrativeArea ?? "unknown"
let storageRef = self.ref.child("drinkingFountains").child(state)
storageRef.observeSingleEvent(of: .value, with: { snapshot in
for child in snapshot.children.allObjects as! [DataSnapshot] {
var dict = child.value as? [String : Any] ?? [:]
let coordinateDistanceFrom = CLLocation(latitude: dict["lat"] as! Double, longitude: dict["long"] as! Double)
let distanceInMeters = currentLocation.distance(from: coordinateDistanceFrom)
dict["distanceFromCurrentLocation"] = String(distanceInMeters)
firebaseArray.append(dict)
}
})
}
}
})
return firebaseArray
}
最佳答案
更新位于索引路径的行的单元格中的代码,如下所示:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let arrayWithFirbaseInfo : Array<Dictionary<String, Any>> = findCordinateFolder()
print(arrayWithFirbaseInfo)
let cell = tableView.dequeueReusableCell(withIdentifier: "customTableCell", for: indexPath) as! NearbyTableViewCell
let isIndexValid = arrayWithFirbaseInfo.indices.contains(indexPath.row)
if isIndexValid {
cell.distanceLabel.text = arrayWithFirbaseInfo[indexPath.row]["favorite drink"] as? String
}
return cell
}
尝试将arrayWithFirbaseInfo移动到viewdidload,而不是在cell for row方法中声明它。
此外,还应使用array.count as修改行数函数
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arrayWithFirbaseInfo.count
}
关于ios - 如何从包含字典的数组中在表 View 中检索和显示数据?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57118633/