将Firebase快照另存为变量以在其他地方使用

时间:2019-04-26 15:08:02

标签: swift firebase firebase-realtime-database

我正在尝试将Firebase快照保存到变量中,以便以后可以使用它重新写入Firebase,但是一旦获取数据,我的应用程序就会崩溃。我意识到我拥有的代码只是获取快照目录,而我的第二次尝试是获取所需的数据,但无法将其分配给变量。

我尝试使用以下方法直接访问数据:

let name = Database.database().reference().child("Users").child(userId!).child("Name")

但这仅返回目录

以下是我要执行的操作:

@IBAction func checkInTapped(_ sender: Any) {

        attendance.text = "Present"

        guard !checkInClicked else {
            UIAlertController.showAlert(message: "ERROR: You can only check in once for this Module!", vc: self)
            return
        }

        let userId = Auth.auth().currentUser?.uid
        let userEmail = Auth.auth().currentUser?.email
        let moduleName = labelText
        let name = Database.database().reference().child("Users").child(userId!).child("Name")
        let currentDate = Date.getCurrentDate()
        let currentTime = Date.getCurrentTime()
        let presence = attendance.text
        let ref = Database.database().reference().child("Attendance").child("Checkin").child(moduleName).child(currentDate).child(userId!)
        let values = ["Email": userEmail!, "Check in Time": currentTime, "Attendance":presence] as [String : Any]
        ref.setValue(values)
        UIAlertController.showAlert(message: "You have checked in!", vc: self)
        checkIn.isEnabled = false
        checkOut.isEnabled = true
    }

我试图将按钮上的所有用户数据保存到Firebase,但同时尝试从数据库中检索“名称”以将其保存到变量中并将其分配给“值”。我还是新手,所以我们将不胜感激

1 个答案:

答案 0 :(得分:0)

声明时实际上并没有从Firebase检索任何数据 let name = Database.database().reference().child("Users").child(userId!).child("Name"),您只是在创建对它的引用,而没有使用引用做任何事情。在没有看到您的数据库结构的情况下,我不确定该代码是否适合您,但请尝试以下操作:

            @IBAction func checkInTapped(_ sender: Any) {
            attendance.text = "Present"

            guard !checkInClicked else {
                UIAlertController.showAlert(message: "ERROR: You can only check in once for this Module!", vc: self)
                return
            }

            //use guard let with optional values to prevent app crashing if value is nil
            guard
            let userId = Auth.auth().currentUser?.uid,
            let userEmail = Auth.auth().currentUser?.email
                else {
                    print("guard let failed: userID, userEmail")
                    return
            }
            let moduleName = labelText
            let nameRef = Database.database().reference().child("Users").child(userId).child("Name")


                // now we need to retrieve data from nameRef       
     nameRef.observeSingleEvent(of: .value, with: { (nameSnap) in
                if let name = nameSnap.value{
                //name has successfully been retrieved from database and safely unwrapped, do whatever you like with it now

                    let currentDate = Date.getCurrentDate()
                    let currentTime = Date.getCurrentTime()
                    let presence = attendance.text
                    let ref = Database.database().reference().child("Attendance").child("Checkin").child(moduleName).child(currentDate).child(userId)
                    let values = ["Email" : userEmail, "Check in Time" : currentTime, "Attendance" : presence] as [String : Any]
                    ref.setValue(values) {
                        (error:Error?, ref:DatabaseReference) in
                        if let error = error {
                            print("Data could not be saved: \(error).")
                        } else {
                            print("Data saved successfully!")

                    UIAlertController.showAlert(message: "You have checked in!", vc: self)
                    checkIn.isEnabled = false
                    checkOut.isEnabled = true
                        }
                    }

                }
            }) { (Error) in
                print("unable to retrieve name from nameRef")
            }
        }

一些注意事项:

  • name现在已成功检索并安全地解包,但是在此之后,代码目前未对其进行任何操作

    • 尝试安全地解开userIDuserEmail之类的可选值,而不是强制使用它们,以防止应用由于强制设置nil值而崩溃。

    • 我还为正在执行的两个firebase函数添加了完成/错误处理,您可以在Firebase文档中找到它们:https://firebase.google.com/docs/database/ios/read-and-write