【问题标题】:Saving firebase snapshot as a variable to use in other places将 firebase 快照保存为变量以在其他地方使用
【发布时间】:2019-04-26 15:08:02
【问题描述】:

我正在尝试将 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,但也尝试从数据库中检索“名称”以将其保存到变量中并将其分配给“值”。我还是 swift 新手,所以任何帮助都将不胜感激

【问题讨论】:

    标签: swift firebase firebase-realtime-database


    【解决方案1】:

    当您声明时,您实际上并没有从 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

    【讨论】:

    • 这实际上与微小的变化完美配合!非常感谢!
    • 如果我必须检索很多项目呢?我需要在if let name = nameSnap.value{ 下添加另一个observeSingleEvent 吗?
    • 很高兴它成功了!如果您需要检索的项目位于不同的位置,那么是的,据我所知,您需要为每个位置创建一个引用并调用。如果它们存储在同一个位置,您可以使用单个引用检索多个值并调用。
    猜你喜欢
    • 2020-05-11
    • 2017-11-10
    • 1970-01-01
    • 1970-01-01
    • 2017-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多