如何使用Firebase确保代码在Swift中按顺序运行?

时间:2018-10-18 21:25:46

标签: ios swift firebase firebase-realtime-database

我正在制作一个运行此代码块的应用程序:

extension LikeOrDislikeViewController: UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        let uid = Auth.auth().currentUser?.uid
        var numRows = 0

        Database.database().reference().child("Num Liked").child(uid!).observeSingleEvent(of: .value, with: { (snapshot) in
            if let dictionary = snapshot.value as? [String: AnyObject] {
                let numMoviesLiked = ((dictionary["Number of Movies Liked"] as? Int))!

                if numMoviesLiked % 4 == 0 {
                numRows = numMoviesLiked/4
                }
            }
        })
        return numRows
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell()
        cell.backgroundColor = UIColor.red
        tableView.rowHeight = 113
        cell.textLabel?.text = "\(indexPath.row)"

        return cell
    }
}

我需要在返回行之前运行“ Database.database ...”代码。我该怎么办?

1 个答案:

答案 0 :(得分:-1)

数据库操作很繁琐,需要一些时间才能完成。您应该在Database.database ...操作完成后更新表视图。

class LikeOrDislikeViewController {
    ...

    lazy var numRows: Int = {
        let uid = Auth.auth().currentUser?.uid
        Database.database().reference().child("Num Liked").child(uid!).observeSingleEvent(of: .value, with: { (snapshot) in
            if let dictionary = snapshot.value as? [String: AnyObject] {
                let numMoviesLiked = ((dictionary["Number of Movies Liked"] as? Int))!

                if numMoviesLiked % 4 == 0 {
                    self.numRows = numMoviesLiked/4
                    self.tableView.reloadData()
                }
            }
        })
        return 0
    }()
}

extension LikeOrDislikeViewController: UITableViewDataSource {

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

    ...
}