简体   繁体   English

从 Firebase 检索用户信息

[英]Retrieving user info from firebase

I know this question is asked a lot, but none of the solutions seem to be working for me(I have been trying multiple solutions from threads like Read data from firebase swift but it doesnt print anything to my console).我知道这个问题被问了很多,但似乎没有一个解决方案对我有用(我一直在尝试从线程中读取多个解决方案,例如从 firebase swift 读取数据,但它没有在我的控制台上打印任何内容)。 I am trying to retrieve the type of user from my database, but I dont know how to.我试图从我的数据库中检索用户的类型,但我不知道如何。

func pushUserInfo(){
    let ref = Database.database().reference()
    let infoDict = ["First name": firstName.text!, "Last name": lastName.text!, "hours": 0, "isUser" : "user"] as [String : Any]
    let users = ref.child("users").child(username)
    users.setValue(infoDict)
}

The part that says ["type": "user"] has two options, either "user" or admin表示 ["type": "user"] 的部分有两个选项,"user" 或 admin 在此处输入图片说明

The screenshot above is of the Firebase realtime database.上面的屏幕截图是 Firebase 实时数据库的截图。 I am trying to retrieve the type of the user, but I have no idea how.我正在尝试检索用户的类型,但我不知道如何。 Please help me figure this out, and if possible, explain the code, because I dont really understand too much about Firebase in general.请帮我解决这个问题,如果可能,请解释代码,因为我对 Firebase 的总体了解并不多。 I tried reading their firebase docs, but I still dont really get it.我尝试阅读他们的 firebase 文档,但我仍然不明白。

It looks like you're setting the data fine except that your username property appears to be a concatenated string of two optionals (maybe firstName.text and lastName.text . So this will make it impossible to query. The first step is to unwrap these into a string:看起来您设置的数据很好,只是您的username属性似乎是两个选项的连接字符串(可能是firstName.textlastName.text 。因此这将无法查询。第一步是解开这些成字符串:

let username = "\(firstName.text!) \(lastName.text!)"

Once you've done that, you can query for that data like this:完成后,您可以像这样查询该数据:

let username = "\(firstName.text!) \(lastName.text!)"
let ref = Database.database().reference().child("users/\(username)")
ref.observeSingleEvent(of: .value, with: { (snapshot) in
  // Now you can access the type value
  let value = snapshot.value as? NSDictionary
  let type = value?["type"] as? String ?? ""
  }) { (error) in
    print(error.localizedDescription)
}

You may also want to reconsider having spaces in your property names (maybe use lastName instead of last name ).您可能还想重新考虑在您的属性名称中包含空格(可能使用lastName而不是last name )。 It will be easier for your code later on.稍后您的代码会更容易。

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

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