【问题标题】:Retrieve Firebase data given a specific field检索给定特定字段的 Firebase 数据
【发布时间】:2017-11-21 13:51:27
【问题描述】:

我正在使用 Firebase,我的数据库如下所示:

Users
   user1
      email: "example1@test.com"
      password: "pass1"
      display name: "Name1"
   user2
      email: "example2@test.com"
      password: "pass2"
      display name: "Name2"

例如,给定使用 Swift 3 的显示名称,我如何检索电子邮件? (例如,如果我知道Name1,则检索到的数据将为example1@test.com。)

【问题讨论】:

  • 我了解如何获取我找到显示名称的所有数据,但我不知道如何通过电子邮件到达确切的字段。我的意思是除了“snapshot.value”我还需要写什么? @NiravD
  • @begood 请检查我下面的答案是否是你所追求的......

标签: ios json swift firebase firebase-realtime-database


【解决方案1】:

如下使用firebase

let dbstrPath : String! = "Users/user1"
self.dbRef.child(dbstrPath).observeSingleEvent(of: .value, with: { (snapshot) in
    if snapshot.exists(){
        print(snapshot.value!)
        // Here you got user value in dict
    }
})

【讨论】:

  • 我认为 OP 是在 query 之后得到他想要的。请参阅我的答案以获取替代方案...
【解决方案2】:

实现以下辅助函数:

func queryEmail(of displayName: String, completion: @escaping (String?) -> Void) {
    let users = FIRDatabase.database().reference().child("Users")
    let query = users.queryOrdered(byChild: "display name").queryEqual(toValue: displayName)
    query.observeSingleEvent(of: .value) {
        (snapshot: FIRDataSnapshot) in
        guard snapshot.exists() else {
            completion(nil)
            return
        }
        let users = snapshot.children.allObjects as! [FIRDataSnapshot]
        precondition(users.count == 1, "Display name isn't unique!")
        let userProperties = users.first!.value as! [String: Any]
        completion(userProperties["email"] as? String)
    }
}

并像这样使用它:

queryEmail(of: "Name1") {
    (email) in
    if let email = email {
        print("Name1 email is \(email)")
    } else {
        print("Email not found")
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-01-19
    • 2018-12-09
    • 1970-01-01
    • 1970-01-01
    • 2018-05-29
    • 2018-01-06
    • 1970-01-01
    相关资源
    最近更新 更多