UITableView无法加载Firebase快照数据。

时间:2017-04-10 12:20:26

标签: ios swift uitableview firebase

我有一个Firebase数据库,其结构如下: "用户" -uid    - 名称     - 电子邮件 。我想输入"用户"将电子邮件和名称放入XCode中的UITableviewController表视图中。数据可以在我的控制台中看到,但不会附加到我的表格视图

class DictionaryTableViewController: UITableViewController {

var ref: FIRDatabaseReference!
let cellID = "Cell"
var refHandle: UInt!
var userList = [Users]()

override func viewDidLoad() {
  super.viewDidLoad()
  //Set firebase database reference
  ref = FIRDatabase.database().reference()

  //Retrieve posts and listen for changes
  refHandle = ref?.child("users").observe(.childAdded, with: { (snapshot) in
     //Code that executes when child is added
     if let dict = snapshot.value as? [String: AnyObject] {
        let user = Users()
        user.name = snapshot.childSnapshot(forPath: "name").value as? String
        print(user.name)
        user.email = snapshot.childSnapshot(forPath: "email").value as? String
        print(user.email)
        print("databaseHandle was called")
        for user in self.userList {
           print(user)
           self.userList.append(user)

        }
        self.tableView.reloadData()
     }
  })
  func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
     return userList.count
  }
  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
     let cell = UITableViewCell(style: .subtitle, reuseIdentifier: cellID)
     cell.textLabel?.text = userList[indexPath.row].name.self
     cell.textLabel?.text = userList[indexPath.row].email.self
     return cell

   }
 }
}

2 个答案:

答案 0 :(得分:0)

删除它:

self.tableView.reloadData()

在if let语句之后添加:

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

答案 1 :(得分:0)

像这样;不会显示表格中的数据。

//Retrieve posts and listen for changes func fetchUserData(with completion:@escaping (Bool)->()) { refHandle = ref?.child("users").observe(.childAdded, with: { (snapshot) in //Code that executes when child is added if (snapshot.value as? [String: AnyObject]) != nil { let user = Users() user.name = snapshot.childSnapshot(forPath: "name").value as? String print(user.name) DispatchQueue.main.async{ user.email = snapshot.childSnapshot(forPath: "email").value as? String print(user.email) print("databaseHandle was called") for user in self.userList { print(user) self.userList.append(user) self.userTable.reloadData() }