如何从包含字典的数组中在表视图中检索和显示数据?

时间:2019-07-19 19:29:22

标签: ios arrays swift uitableview firebase-realtime-database

我正在尝试从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
}

1 个答案:

答案 0 :(得分:1)

更新单元格中位于索引路径的行中的代码,如下所示:

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,而不是在行方法的单元格中声明它。 另外,您应该使用array.count修改行数功能为

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
   return arrayWithFirbaseInfo.count
}