且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

(Firebase)在计算用户数组时计算数据库中的用户数量错误

更新时间:2023-12-02 14:17:34

下面。就像Ahmed说的那样:获取数据需要一些时间,因为它是异步的。

  func getUsers(completionHandler:@escaping( ()()){

let ref = Database.database()。reference()。child(users)

ref.observe(.childAdded ,如下:{(snapshot)in
if let dictionary = snapshot.value as?[String:AnyObject] {

let user = User()

user .id = snapshot.key
user.setValuesForKeys(dictionary)
self.users.append(user)
completionHandler(self.users.count)
}
} )

重写func viewDidLoad(){
super.viewDidLoad()
getUsers(){(count)in
print(count)
}



$ b $ p
$ b

这很简单,我刚刚添加了一个完成处理程序。 / p>

I am retrieving a snapshot of all of the users in my Firebase database. After I append all of my users from my "users" node of my database to an array of users , I attempt to print the user count (which should be 12) and it says it is 0 instead.

I added a breakpoint at the closing brace of the if-statement which shows to me that the user count reaches 12. However, by the time it comes time to print this number, it is zero. Stepping through a bunch of times is just a lot of assembly code that tells me nothing.

I call this function in the viewDidLoad() method and tried to print the users count after this function is called in addition to printing it within the function and it is still 0.

func getUsers() {

    let ref = Database.database().reference().child("users")

    ref.observe(.childAdded, with: { (snapshot) in
        if let dictionary = snapshot.value as? [String: AnyObject] {

            let user = User()

            user.id = snapshot.key
            user.setValuesForKeys(dictionary)                
            self.users.append(user)
        }

    }, withCancel: nil)

    print(users.count)
}

Here you go, a fix below. Like Ahmed is saying: it takes some time to get the data since it is async.

func getUsers(completionHandler:@escaping (Int) -> ()){

    let ref = Database.database().reference().child("users")

    ref.observe(.childAdded, with: { (snapshot) in
        if let dictionary = snapshot.value as? [String: AnyObject] {

            let user = User()

            user.id = snapshot.key
            user.setValuesForKeys(dictionary)
            self.users.append(user)
            completionHandler(self.users.count)
        }
    })

override func viewDidLoad() {
    super.viewDidLoad()
    getUsers(){ (count) in
        print(count)
    }
}

It is pretty straightforward what is going on, I just added a completion handler.