首页 > 解决方案 > 当节点值未知/自动生成 Swift 时更新 Firebase 中的子值

问题描述

我的应用程序中有一个搜索功能,它可以从数据库返回值并在我的屏幕上填充文本视图。我想要实现的是,如果更新了 textview 的值,我们可以按下保存按钮,并且从搜索返回的值在相同的 db ID 下更新。

这是我的数据库结构: 在此处输入图像描述

这是我正在尝试实现的更新方法:

func updateRecord(){

    guard let pub: String = searchText.text?.lowercased() else { return }

    let databaseRef = Database.database().reference().child("Drinks")


    let query = databaseRef.queryOrdered(byChild: "pub").queryStarting(atValue: pub).queryEnding(atValue: "\(String(describing: pub))\\uf8ff")

    query.observeSingleEvent(of: .value) { (snapshot) in
        guard snapshot.exists() != false else {

            print("Error, doesn't exist")

            return
        }
        DispatchQueue.main.async {

            let signature = "E"


            //adding drink data
            let drink = [
                "pub": self.pubName.text!.lowercased() as String,
                "location": self.pubLocation.text!.lowercased() as String,
                "price": self.price.text!.lowercased() as String,
                "rating": self.rating.text!.lowercased() as String,
                "comment": self.comment.text!.lowercased() as String,
                "signature": signature
            ]
            databaseRef.child(--How do I access this token, for the drink in the picture I need to get "Lzsx_Vv5x5WVFsig-Zl"--).setValue(drink)

            return
        }
    }
}

基本上在我的数据库中,我需要能够访问存储数据的自动生成的 ID。我知道“updateChildValues”方法可以工作,或者在我再次存储信息时再次“setValue”,但我如何访问存储数据的 ID?

谢谢, 乙

标签: swiftfirebasefirebase-realtime-database

解决方案


我不能 100% 确定,因为我已经一年没有使用 Firebase。但请尝试以下。

query.observeSingleEvent(of: .value) { (snapshot) in
    if snapshot.childrenCount > 0 {
        for drink in snapshot.children.allObjects as! [DataSnapshot] {
            let id = drink.key; print(id)
        }
    }
}

推荐阅读