尝试使用Swift从Firestore集合中检索的数据填充TableView,但是它为空

时间:2019-07-20 10:19:25

标签: ios swift firebase google-cloud-firestore tableview

我真的是使用swift进行IOS开发的新手,我想知道为什么当我尝试用从Firestore集合中检索到的数据填充TableView时收到一个空的TableView。

完全没有错误。我尝试

时会收到数据
print()

是因为SnapshotListener吗?

import UIKit
import FirebaseStorage
import FirebaseFirestore

struct Posts {
   var caption:String
}

class LentaViewController: UIViewController {
  @IBOutlet weak var tableView: UITableView!
  var posts = [Posts]()

override func viewDidLoad() {
    super.viewDidLoad()
    loadPosts()

    DispatchQueue.main.async {
        self.tableView.reloadData()
    }
 }

 func loadPosts() {
    let dbUsers = Firestore.firestore().collection("posts")
    dbUsers.addSnapshotListener { (querySnapshot, error) in
        if let error = error {
            print("\(error.localizedDescription)")
        } else {
            for document in (querySnapshot?.documents)! {
                if let Caption = document.data()["caption"] as? String {
                    print(Caption)
                    var post = Posts(caption: "")
                    post.caption = Caption

                    self.posts.append(post)
                }

            }
            DispatchQueue.main.async
            {
                self.tableView.reloadData()
            }
            print(self.posts)
        }
    }
  }
}

extension LentaViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return posts.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
    let post = posts[indexPath.row]
    cell.textLabel?.text = post.caption
    return cell
 }
}

1 个答案:

答案 0 :(得分:0)

您没有将tableView.dataSource属性分配给LentaViewController实例。在viewDidLoad()中分配它。另外,无需在ViewDidLoad()中重新加载tableView。

override func viewDidLoad() {
   super.viewDidLoad()
   tableView.dataSource = self
   loadPosts()
}