使用 ChildAdded 使用 swift 4 从 firebase 数据库中获取第一个密钥

Fetch first key from firebase database with swift 4 using ChildAdded

我正在尝试从我的 firebase 数据库中获取第一个密钥,但由于某种原因没有打印出任何内容。如何使用 .childAdded

从我的 firebase 数据库中获取第一个密钥
let userMessagesRef = Database.database().reference().child("user-message").child(uid).child(userId)
    userMessagesRef.observe(.childAdded, with: { (snapshot) in

        guard let first = snapshot.children.allObjects.first as? DataSnapshot else { return }
        print(first)

The child_added event is typically used when retrieving a list of items from the database. Unlike value which returns the entire contents of the location, child_added is triggered once for each existing child and then again every time a new child is added to the specified path. The event callback is passed a snapshot containing the new child's data. For ordering purposes, it is also passed a second argument containing the key of the previous child.

发件人:Read and Write Data on iOS

根据您的要求,这在 .valuechildAdded 中是可能的。

var child_array = [String:String]
let userMessagesRef = Database.database().reference().child("user-message").child(uid).child(userId)
    userMessagesRef.observe(.childAdded, with: { (snapshot) in
        let value = snapshot.value as? String ?? "Empty String"
        let key = snapshot.key 
        child_array[key] = value;


        }) { (error) in
    print(error.localizedDescription)
}

然后:

if let first = child_array.first?.key {
    print(first)  // First Key
}

Big NOTE: child_added randomly collects this data, you should never use it to sort your data

如果您真的要问如何只获取节点的第一个子节点,这将非常容易。以下是如何只获取 /users 节点的第一个子节点

func getFirstChild() {
    let usersRef = self.ref.child("users")
    usersRef.observeSingleEvent(of: .childAdded, with: { snapshot in
        print(snapshot)
    })
}

print(snapshot.key)

如果你只想要钥匙。

或者,如果您想使用查询来做同样的事情

func getFirstChildAgain() {
    let usersRef = self.ref.child("users")
    let query = usersRef.queryOrderedByKey().queryLimited(toFirst: 1)
    query.observeSingleEvent(of: .value, with: { snapshot in
        print(snapshot)
    })
}