gpt4 book ai didi

ios - 如何在 Swift 中从 Firebase 数据库检索变量

转载 作者:行者123 更新时间:2023-11-30 11:02:42 25 4
gpt4 key购买 nike

我试图简单地读入结构如下所示的数据库。我试图读取用户的“userType”并在下面的 if 语句中使用它。如有任何帮助,我们将不胜感激!

快速代码:

// Create firebase reference and link to database
var dataRef : DatabaseReference?
dataRef = Database.database().reference()
let userID = Auth.auth().currentUser!.uid // Get the User's ID

// Gather user's type (Customer or Company)
/*Use this space to gather the user's type into some variable named currUserType*/


if (currUserType == "Customer"){
self.performSegue(withIdentifier: "LoginToCustomer", sender: self)
print("User: " + userID + " has been signed in!")
}
else if (currUserType == "Company"){
self.performSegue(withIdentifier: "LoginToHost", sender: self)
}
else{
self.showMessage(alertTitle: "Error",
alertMessage: "Please report the following error with a description of what lead to to the error.",
actionTitle: "Dismiss")
}

数据库结构:

"Users" : {
"ZFH0lFe1fIb5bwSO2Q95ektD33L2" : {
"email" : "cust@test.com",
"userType" : "Customer"
}

最佳答案

  1. 首先采用我在下面采用的引用:

let dbRef = Database.database().reference().child("Users")

  • 然后创建模型,就像我在下面创建的那样:
  • class Users { var email: String? var userType: String?

    init(email: String, userType: String) {
    self.email = email
    self.userType = userType
    }

    }

  • 然后创建完成处理程序,就像我在下面创建的那样:
  • func getUsersData(handler: @escaping (_ usersArray: [Users]) -> ()) {
    var usersArray = [Users]()

    dbRef.observe(.value) { (datasnapshot) in

    guard let usersnapshot = datasnapshot.children.allObjects as? [DataSnapshot] else { return }

    for user in usersnapshot {
    let email = user.childSnapshot(forPath: "email").value as! String
    let userType = user.childSnapshot(forPath: "userType").value as! String

    let userObj = Users(email: email, userType: userType)
    usersArray.append(userObj)
    }
    handler(usersArray)
    }

    }

  • 只需调用此函数即可返回整个用户数组。
  • 引用https://firebase.google.com/docs/database/ios/read-and-write#reading_and_writing_data

    关于ios - 如何在 Swift 中从 Firebase 数据库检索变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53127720/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com