且构网

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

Firebase Swift检查用户(如果存在)无法正常运行

更新时间:2023-11-28 13:39:34

从Firebase加载数据是异步进行的.这意味着打印成功的代码将在实际加载数据之前运行.最简单的方法是使用一些适当的日志语句:

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

附加观察者之后

数据已加载

无法更改此行为.这只是大多数现代网络的工作方式.

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!)
    }
})