如何从Firebase读取数据,阻止与行不通?

时间:2019-03-26 08:06:50

标签: swift firebase firebase-realtime-database

我尝试从Firebase读取数据。我已经创建了observeSingleEvent,但是阻止“ with”不起作用,为什么?

我尝试调试,但是我注意到该块不起作用。 userID具有正确的ID 并且引用也正确

    var ref: DatabaseReference!
    var snapData: NSDictionary?
    var nameString = [String]()

    override func viewDidLoad() {
        super.viewDidLoad()

        ref = Database.database().reference()
        loadData()
        table.delegate = self
        table.dataSource = self
        table.register(UITableViewCell.self, forCellReuseIdentifier: "indentifire")
        view.addSubview(table)


        // Do any additional setup after loading the view.
    }

    // ---------------------------------------------------

    //loading data from FireBase
    func loadData() {
        let userID = Auth.auth().currentUser?.uid
        ref.child("users").child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in
            self.snapData = snapshot.value as? NSDictionary
        })
    }

    // delegate
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        var temp = 0
        for (_,val) in snapData! {
            if val as? String == "false" {
                temp += 1
                nameString.append(val as! String)
            }
        }
        return temp
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = table.dequeueReusableCell(withIdentifier: "indentifire", for: indexPath)
        cell.textLabel!.text = nameString[indexPath.row]
        return cell
    }```

this is my database
![photo](https://imgur.com/a/0UzOPJ7

1 个答案:

答案 0 :(得分:0)

数据库操作异步进行。映射loadData中的数据并重新加载表格视图

func loadData() {
    let userID = Auth.auth().currentUser?.uid
    ref.child("users").child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in
        if let snapData = snapshot.value as? [String:Any] {
           self.nameString = snapData.values.compactMap {$0 as? String}
           DispatchQueue.main.async {
              self.table.reloadData()
           }
        }
    })
}

然后在numberOfRowsInSection中返回nameString中的项目数

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