简体   繁体   English

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

[英]How to retrieve a variable from a Firebase Database in Swift

I am attempting to simply read into the database that is structured as stated below. 我试图简单地读入结构如下所述的数据库。 I am attempting to read the user's "userType" and use it in the following if statements below. 我正在尝试读取用户的“ userType”,并在下面的if语句中使用它。 Any help is appreciated! 任何帮助表示赞赏!

Swift Code: SWIFT代码:

// 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")
}

Database Structure: 数据库结构:

"Users" : {
"ZFH0lFe1fIb5bwSO2Q95ektD33L2" : {
  "email" : "cust@test.com",
  "userType" : "Customer"
}
  1. First take the ref like i have took below: 首先像我在下面那样拿裁判:

let dbRef = Database.database().reference().child("Users") 让dbRef = Database.database()。reference()。child(“ Users”)

  1. Then create model like i have created below: 然后像我在下面创建的那样创建模型:

class Users { var email: String? class Users {var email:String? var userType: String? var userType:字符串?

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

} }

  1. Then create completion Handler like i have created below: 然后像我在下面创建的那样创建完成处理程序:
 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)
}

} }

  1. simply call this function which returns the whole array of users. 只需调用此函数即可返回整个用户数组。

Refrence https://firebase.google.com/docs/database/ios/read-and-write#reading_and_writing_data 刷新https://firebase.google.com/docs/database/ios/read-and-write#reading_and_writing_data

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM