TableView不显示Swift中检索到的Firebase Cloud Firerestore数据

rbl8hiat  于 2023-08-02  发布在  Swift
关注(0)|答案(1)|浏览(142)

我正在创建一个虚拟的社交媒体应用程序,但UITableView的行为并不是我所期望的。数据检索操作后,UITableView未显示提取的内容。下面是我的FeedViewController的代码:

  1. import UIKit
  2. import FirebaseFirestore
  3. class FeedViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
  4. @IBOutlet weak var tableView: UITableView!
  5. var postArray = [[String: Any]]()
  6. override func viewDidLoad() {
  7. super.viewDidLoad()
  8. tableView.delegate = self
  9. tableView.dataSource = self
  10. getDataFromFirestore(){
  11. print("self.tableView.reloadData() called from viewDidLoad()")
  12. self.tableView.reloadData()
  13. }
  14. }
  15. override func viewDidAppear(_ animated: Bool) {
  16. print("self.tableView.reloadData() called from viewDidAppear()")
  17. self.tableView.reloadData()
  18. }
  19. func getDataFromFirestore(completion: @escaping() -> Void){
  20. let ref = Firestore.firestore().collection("posts")
  21. ref.addSnapshotListener { snapshot, error in
  22. if error != nil {
  23. self.makeAlert(title: "Error", message: error?.localizedDescription ?? "An error occoured during the process.")
  24. } else {
  25. if !(snapshot?.isEmpty ?? true) {
  26. for doc in snapshot!.documents {
  27. var dict = [String: Any]()
  28. dict["userID"] = doc.get("userID") as? String
  29. dict["comment"] = doc.get("comment") as? String
  30. dict["imageURL"] = doc.get("imageURL") as? String
  31. dict["likes"] = doc.get("likes") as? String
  32. self.postArray.append(dict)
  33. }
  34. }
  35. print("self.postArray.count been accessed from getDataFromFirestore(): \(self.postArray.count)")
  36. }
  37. }
  38. completion()
  39. }
  40. func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  41. let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! FeedCell
  42. cell.lblUserEmail.text = self.postArray[indexPath.row]["userID"] as! String? ?? ""
  43. cell.lblLikes.text = self.postArray[indexPath.row]["likes"] as! String? ?? ""
  44. cell.lblUserComment.text = self.postArray[indexPath.row]["comment"] as! String? ?? ""
  45. return cell
  46. }
  47. func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  48. print("self.postArray.count been accessed from numberOfRowsInSection: \(self.postArray.count)")
  49. return postArray.count
  50. }
  51. func makeAlert(title: String, message: String) {
  52. let controller = UIAlertController(title: title, message: message, preferredStyle: UIAlertController.Style.alert)
  53. let action = UIAlertAction(title: "OK", style: UIAlertAction.Style.default)
  54. controller.addAction(action)
  55. self.present(controller, animated: true)
  56. }
  57. }

字符串

控制台输出:

  1. self.tableView.reloadData() called from viewDidLoad()
  2. self.postArray.count been accessed from numberOfRowsInSection: 0
  3. self.postArray.count been accessed from numberOfRowsInSection: 0
  4. self.postArray.count been accessed from numberOfRowsInSection: 0
  5. self.tableView.reloadData() called from viewDidAppear()
  6. self.postArray.count been accessed from numberOfRowsInSection: 0
  7. self.postArray.count been accessed from getDataFromFirestore(): 1


下面是我的UITableViewCell的代码:

  1. import UIKit
  2. class FeedCell: UITableViewCell {
  3. @IBOutlet weak var lblUserComment: UILabel!
  4. @IBOutlet weak var lblUserEmail: UILabel!
  5. @IBOutlet weak var imgView: UIImageView!
  6. @IBOutlet weak var lblLikes: UILabel!
  7. override func awakeFromNib() {
  8. super.awakeFromNib()
  9. // Initialization code
  10. }
  11. override func setSelected(_ selected: Bool, animated: Bool) {
  12. super.setSelected(selected, animated: animated)
  13. // Configure the view for the selected state
  14. }
  15. @IBAction func btnLikeClicked(_ sender: Any) {
  16. }
  17. }

Firestore数据:

屏幕输出(空白,无数据):


guykilcj

guykilcj1#

你在监听器外调用完成。因此完成将不会等待响应和重新加载TableView。

  1. func getDataFromFirestore(completion: @escaping() -> Void){
  2. let ref = Firestore.firestore().collection("posts")
  3. ref.addSnapshotListener { snapshot, error in
  4. if error != nil {
  5. self.makeAlert(title: "Error", message: error?.localizedDescription ?? "An error occoured during the process.")
  6. } else {
  7. if !(snapshot?.isEmpty ?? true) {
  8. for doc in snapshot!.documents {
  9. var dict = [String: Any]()
  10. dict["userID"] = doc.get("userID") as? String
  11. dict["comment"] = doc.get("comment") as? String
  12. dict["imageURL"] = doc.get("imageURL") as? String
  13. dict["likes"] = doc.get("likes") as? String
  14. self.postArray.append(dict)
  15. }
  16. }
  17. print("self.postArray.count been accessed from getDataFromFirestore(): \(self.postArray.count)")
  18. completion()
  19. }
  20. }
  21. }

字符串
就这样做,享受吧:)

展开查看全部

相关问题