Firebase - Swift - 从快照中删除子UID

时间:2017-09-13 17:04:15

标签: swift firebase firebase-realtime-database

enter image description here

我正在尝试从我的staffUsers中删除studentUser UID。我要删除的UID嵌套在staffUsers中 - > studentSession1List。 我在创建时使用A Bool of True列出了UID。这个“studentSession1List”将在列表中包含许多studentUsers。我只希望登录的studentUser从列表中删除它们的UID(55FDLm9n6LccZBB7skaCbvfSHRz1)。

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

    dataref.child("staffUsers").queryOrdered(byChild: "studentSession1List").observe(.value, with: { (snapshot) in


        for snap in snapshot.children {
            guard let studentUID = Auth.auth().currentUser?.uid else { return }

            let snapDataSnapshot = snap as! DataSnapshot

            var snapValues = snapDataSnapshot.value as? [String: AnyObject]

            if var snapWithReg = snapValues?["studentSession1List"] as? [String: Bool] {


                print("This is the staff member")
                print(snapWithReg)
                print(snapWithReg.count)
                snapWithReg.removeValue(forKey: studentUID)
            }

        }


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

    }

这是输出:

enter image description here

删除和添加学生的全部功能

    func didSelect(for cell: StudentSearchCell) {
    guard let indexpath = collectionView?.indexPath(for: cell) else { return }
    let staffUser = self.users[indexpath.item]
    let selectedUserId = staffUser.uid
    guard let studentUID = Auth.auth().currentUser?.uid else { return }

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

    dataRef.child("staffUsers").queryOrdered(byChild: "studentSession1List").observe(.value, with: { (snapshot) in


        for snap in snapshot.children {
            guard let studentUID = Auth.auth().currentUser?.uid else { return }

            let snapDataSnapshot = snap as! DataSnapshot

            var snapValues = snapDataSnapshot.value as? [String: AnyObject]

            if (snapValues? ["studentSession1List"] as? [String: Bool]) != nil {
                dataRef.child("staffUsers").child(snapDataSnapshot.key).child("studentSession1List").child(studentUID).removeValue(completionBlock: { (error, ref) in
                    if error != nil {
                        print("Error: \(String(describing: error))")
                        return
                    }
                    print("Removed successfully")

                })

            }

        }


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

    }



    // Add student to staff list
    let ref = Database.database().reference().child("staffUsers").child(selectedUserId).child("studentSession1List")
    let values = [studentUID: true]
    ref.updateChildValues(values) { (err, ref) in
        if let err = err {
            print("Failed to follow user:", err)
            return

        }
    }

    // Add selected staff to student list
    let studentRef = Database.database().reference().child("studentUsers").child(studentUID).child("studentSession1List")
    studentRef.removeValue()
    let studentValues = [selectedUserId: true]
    studentRef.updateChildValues(studentValues) { (err, studentRef) in
        if let err = err {
            print("Failed to follow user:", err)
            return

        }
    }

    self.navigationController?.popViewController(animated: true)
}

1 个答案:

答案 0 :(得分:1)

我认为你需要使用以下代码联系要删除的孩子,然后将其删除。

<强> EDIT1:

由于在 staffUsers 内部,我们在其中存在 studentSession1List 的密钥,其中存在我们要删除的值(studentUID),所以在你已编写的代码中我添加了新代码,请检查

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

    dataref.child("staffUsers").queryOrdered(byChild: "studentSession1List").observe(.value, with: { (snapshot) in


        for snap in snapshot.children {
            guard let studentUID = Auth.auth().currentUser?.uid else { return }

            let snapDataSnapshot = snap as! DataSnapshot

            var snapValues = snapDataSnapshot.value as? [String: AnyObject]

            if var snapWithReg = snapValues?["studentSession1List"] as? [String: Bool] {

                //Added code here
                dataref.child("staffUsers").child(snapDataSnapshot.key).child("studentSession1List").child(studentUID).removeValue(completionBlock: { (error, ref) in
                    if error != nil {
                          print("Error: \(error)")
                          return
                    }
                    print("Removed successfully")

                })

            }

        }


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

    }

<强> EDIT2:

要删除一次代码,我们可以使用observeSingleEvent

observeSingleEvent(of: .value, with: { (snapshot) in

                        }, withCancel: nil)