Firebase Swift check user if exists not working properly

♀尐吖头ヾ 提交于 2020-07-11 06:02:34

问题


I'm trying to check if a user exists in my database but it always says "Success" no matter if the user exists or not. I don't really understand FireBase docs, they are pretty poor, can anyone help me and tell me why I get success everytime?

        if nickTextField.text != "" {

    let db = Database.database().reference()

        var userExistsSwitch = false
        db.child("Usernames").observe(.value, with: { (snapshot) in
            if snapshot.hasChild("\(self.nickTextField.text!)") {
                userExistsSwitch = true
                print("Username already exists!")
            }
        })

        db.child("Usernames").removeAllObservers()

        if !userExistsSwitch {
            print("Success!")
            db.child("Usernames").child(self.nickTextField.text!).setValue(self.nickTextField.text!)
        }

    }

回答1:


Loading data from Firebase happens asynchronously. This means that your code that prints success runs before the data has actually loaded. The easiest way to see this is with a few well places log statements:

let db = Database.database().reference()
print("Before attaching observer");
db.child("Usernames").observe(.value, with: { (snapshot) in
    print("Data has loaded");
})
print("After attaching observer");

When you run this code, it prints:

Before attaching observer

After attaching observer

Data has loaded

There is no way to change this behavior. It is simply the way most of the modern web works.

This means that you'll have to put any code that requires the data into the completion handler, or call it from within the completion listener. An easy way to do this in your case:

let db = Database.database().reference()

var userExistsSwitch = false
db.child("Usernames").observe(.value, with: { (snapshot) in
    db.child("Usernames").removeAllObservers()
    if snapshot.hasChild("\(self.nickTextField.text!)") {
        userExistsSwitch = true
        print("Username already exists!")
    }
    if !userExistsSwitch {
        print("Success!")
        db.child("Usernames").child(self.nickTextField.text!).setValue(self.nickTextField.text!)
    }
})


来源:https://stackoverflow.com/questions/47542744/firebase-swift-check-user-if-exists-not-working-properly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!