使用Swift从Firebase读取单个值

时间:2022-09-08 21:25:04

I've been dying because of this problem.

因为这个问题,我一直在死。

Let me show you my Swift code first:

让我先向您展示我的Swift代码:

@IBOutlet weak var testLabel: UILabel!
@IBOutlet weak var phoneTextField: UITextField!

var dbRef : DatabaseReference!
dbRef = Database.database().reference()

if let text = phoneTextField.text, !text.isEmpty {
    dbRef.child("user").observeSingleEvent(of: .childAdded) {    
        (snapshot) in
        let phoneDB = snapshot.value as? String
        self.testLabel.text = phoneDB
    }
}

and this is my Firebase database:

这是我的Firebase数据库:

project-2ac-33
 -user
   -name : "user1"
   -phone : 1111
   -password : 1234 

What I want to do is: if I type any number in the phoneTextField then testLabel shows me 1111 (real phone value in Firebase).

我想要做的是:如果我在phoneTextField中输入任何数字,那么testLabel会显示1111(Firebase中的真实电话价值)。

But when I run this project, testLabel shows me user1 instead (value from Firebase) not a phone value.

但是当我运行这个项目时,testLabel会向我显示user1(来自Firebase的值)而不是电话值。

Can anyone help me please?

有人可以帮我吗?

1 个解决方案

#1


6  

Try this instead:

试试这个:

...
dbRef.child("user/phone").observeSingleEvent(of: .value) { 
    (snapshot) in
    if let phoneDB = snapshot.value as? Int {
        self.testLabel.text = "\(phoneDB)"
    }
}

You were reading all user children, which also includes the password and name nodes. The above code reads only the desired user/phone value instead ;)

您正在读取所有用户子节点,其中还包括密码和名称节点。以上代码只读取所需的用户/电话值;)

Also note that I'm now using .value instead of .childAdded as well.

另请注意,我现在使用.value而不是.childAdded。

#1


6  

Try this instead:

试试这个:

...
dbRef.child("user/phone").observeSingleEvent(of: .value) { 
    (snapshot) in
    if let phoneDB = snapshot.value as? Int {
        self.testLabel.text = "\(phoneDB)"
    }
}

You were reading all user children, which also includes the password and name nodes. The above code reads only the desired user/phone value instead ;)

您正在读取所有用户子节点,其中还包括密码和名称节点。以上代码只读取所需的用户/电话值;)

Also note that I'm now using .value instead of .childAdded as well.

另请注意,我现在使用.value而不是.childAdded。