在给定特定字段的情况下检索Firebase数据

时间:2017-06-19 11:09:41

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

我正在使用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。)

2 个答案:

答案 0 :(得分: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
    }
})

答案 1 :(得分:0)

实现以下辅助函数:

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