2017-06-19 60 views
1

我使用火力地堡和我的數據庫看起來是這樣的:找回火力地堡數據給出了具體的領域

Users 
    user1 
     email: "[email protected]" 
     password: "pass1" 
     display name: "Name1" 
    user2 
     email: "[email protected]" 
     password: "pass2" 
     display name: "Name2" 

如何取回例如電子郵件,給出了使用斯威夫特3的顯示名稱? (例如,如果我知道Name1,檢索到的數據將[email protected]。)

+0

相關:https://stackoverflow.com/questions/43971814/firebase-querying-for-unique- username-swift –

+0

我知道如何獲取所有顯示名稱的數據,但我不知道如何通過電子郵件到達確切的字段。我的意思是除了「snapshot.value」之外還需要寫些什麼? @NiravD – alecs09

+0

@begood請檢查我的答案是否是你之後的... –

回答

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

使用火力如下

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 
    } 
}) 
+0

我認爲OP是在* query *之後得到他想要的。請參閱我的答案以獲得替代方案... –