2016-06-11 103 views
6

我試圖從當前登錄的用戶檢索特定數據。我在我的數據庫中的數據是這樣的:Firebase檢索Swift中的數據

enter image description here

舉例來說,我只想抓住FULL_NAME並將其保存在一個變量名。下面是我用來抓取我的數據

ref.queryOrderedByChild("full_name").queryEqualToValue("userIdentifier").observeSingleEventOfType(.ChildAdded, withBlock: { snapshot in 
      print(snapshot.value) 
      // let userName = snapshot.value["full_name"] as! String 
     }) 

不幸的是,這是我的控制檯打印。

enter image description here

我希望得到任何幫助:)謝謝!

+0

哎添。你在做認證嗎?你在用什麼? – adolfosrs

+0

即時嘗試將數據保存到本地變量,所以我可以用它來顯示的東西:-) – Tim

回答

10

由於您正在進行查詢,因此會顯示該警告消息indexOn

您應該通過安全和Firebase規則中的.indexOn 規則來定義要編入索引的密鑰。當你被允許 在客戶端上創建這些查詢臨時,你會使用.indexOn

當看到大大 提高性能

你知道你正在尋找你的名字可以直接到該節點,沒有查詢。

let ref:FIRDatabaseReference! // your ref ie. root.child("users").child("[email protected]") 

    // only need to fetch once so use single event 

    ref.observeSingleEventOfType(.Value, withBlock: { snapshot in 

     if !snapshot.exists() { return } 

     //print(snapshot) 

     if let userName = snapshot.value["full_name"] as? String { 
      print(userName) 
     } 
     if let email = snapshot.value["email"] as? String { 
      print(email) 
     } 

     // can also use 
     // snapshot.childSnapshotForPath("full_name").value as! String 
    }) 
+0

Xcode建議我添加一個「!」在我不確定的價值之後是我們應該做的事情......事實上,這可能是導致它崩潰的原因(?) – Tim

+0

它是一個可選的力量 - 如果該值不存在,它會崩潰。 – DogCoffee

+0

還取決於您的模型設計,您可能會收回多個快照。那麼你會使用snapshot.children並遍歷它們。本教程適用於這些基礎知識https://www.raywenderlich.com/109706/firebase-tutorial-getting-started-火焰基礎入門指南也非常好! https://firebase.google.com/docs/ios/setup – DogCoffee

2
{ 
    "rules": { 
     "tbl_name": { 
      ".indexOn": ["field_name1", "field_name2"] 
     }, 
    ".read": true, 
    ".write": true 
    } 
} 

您可以在任何領域應用indexOn。在規則安全性和規則選項卡中添加此json。 希望這對你有用。 :)

2

它檢索登錄的用戶數據:

let ref = FIRDatabase.database().reference(fromURL: "DATABASE_URl") 
let userID = FIRAuth.auth()?.currentUser?.uid 
let usersRef = ref.child("users").child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in 
print(snapshot) 
0

夫特4

let ref = Database.database().reference(withPath: "user") 
    ref.observeSingleEvent(of: .value, with: { snapshot in 

     if !snapshot.exists() { return } 

     print(snapshot) // Its print all values including Snap (User) 

     print(snapshot.value!) 

     let username = snapshot.childSnapshot(forPath: "full_name").value 
     print(username!) 

    })