如何在firebase数据库的子级中获取value []

时间:2018-10-23 16:46:34

标签: ios swift firebase firebase-realtime-database

我的代码中有一行代码,其中应提取子代“ ”中子代“ profilepicture ”中 userID 的值用户”,但我不知道该如何在内部写入值[]。有人可以帮我吗?

let ref = Database.database().reference()
ref.child("users").queryOrderedByKey().observeSingleEvent(of: .value,         
    let users = DataSnapshot.value as! [String: AnyObject]
    self.user.removeAll()
    for (_, value) in users{
        //let uid = Auth.auth().currentUser!.uid
        if let uid = value["profilepicture.userID"] as? String

1 个答案:

答案 0 :(得分:1)

您的节点users似乎是一个数组。因此,这很大程度上取决于您要设置哪个用户的userID。因此,使用您的代码,尝试必须遵循以下步骤

let dbQuery = dbRef.child("users")
dbQuery.observeSingleEvent(of: .value, with: { (snapshot) in
        for child in snapshot.children {
            if  let dataSnapshot = child as? DataSnapshot,
                let valueDict = dataSnapshot.value as? [String: Any] {
                // here valueDict is each user as dictionary
                // here you will need a mechanism to identify the user
                // of which you want to set the `userID` value
                let key = dataSnapshot.key // each users key

                if /* your logic to identify the user based on the key. If this logic satisfy then set it's value */ {
                       dbRef.child("users").child(key).child("profilepicture").child("userID").setValue(YOUR_DESIRED_VALUE_TO_SET)

                   // OPTIMIZATION: if this meant to happen only once use `break` to get out of the loop, because you don't need to iterate the whole loop.
                } 
            }
        }
        print("YOU ARE DONE UPDATING")
    })