2017-02-17 24 views
0

並感謝您的幫助!firebase Databse Query Swift沒有閱讀

我的應用程序的每個用戶都會回答一系列問題。我已經成功地在結構如下書面這些問題的答案,以我的數據庫(呀我!)(見附件PIC太link to database structure): 數據庫結構:

 - driverQuestions 
      - 'userId' (this the UID generated at authentication) 
      - answers (this is the answer that I need to display in the users profile for future reference 
      - questions (this is the question that the user has answered) 

的數據庫規則:

{ 
    "rules": { 
    "driverQuestions": { 
     "$userId": { 
     ".indexOn": "answers" 
     } 
    }, 
    ".read": "auth != null", 
    ".write": "auth != null" 
    } 
} 

我曾嘗試用以下代碼查詢我的數據庫:

import FirebaseDatabase 
import Firebase 
import FirebaseAuth 

let userId = FIRAuth.auth()?.currentUser?.uid 
var ref: FIRDatabaseReference! 

ref?.child("driverQuestions").child(userId!).child("answers").queryOrdered(byChild: "answers").queryEqual(toValue: userId).observe(.value, with: { (snapshot) in 
      let postDict = snapshot.value as? [String : AnyObject] ?? [:] 
       print(postDict) 

我的領事上沒有打印任何東西。我認爲這個問題是userId是唯一的,但我不知道該怎麼做......你能告訴我我做錯了什麼,以及我需要做些什麼來獲得存儲答案出來的數據庫爲登錄用戶的

讓我知道如果你再

由於需要任何進一步澄清的時間和幫助

回答

0

的問題是,您要查詢的答案結點,而不是用戶,對於具有鍵「答案」的子節點,您的帖子似乎並不存在,除非您在答案JSON中有進一步的嵌套節點。否則,請更新您的完整數據結構並讓我知道。所以你正在尋找driverQuestions/userId/answers/answers而不是driverQuestions/userId/answers

刪除了示例代碼,這是無關緊要的。

嘗試使用此方法獲得的所有數據打印到控制檯上的用戶:

FIRDatabase.database().reference().child("driverQuestions").child(userId!).observe(.value, with: {snapshot in 
    let answersData = snapshot.value as? [String:Any] ?? [:] 
    print(answersData) 
}) 
+0

感謝您在百忙之中閱讀我的文章的時候了!很好的解釋,這是有道理的......不幸的是沒有任何東西被印在領事!任何其他建議?你確定我的代碼與userId是正確的嗎?任何其他建議如何處理使用唯一的ID? – theGuiza

+0

你有數據結構的方式將工作。驅動程序問題的節點,隨機UID密鑰以及該節點的數據。我更新了我的答案,以獲取所有用戶數據,而不僅僅是傳入用戶的答案節點中的數據。也許你傳遞的UID沒有答案數據,不會打印任何內容。 – matthew

+0

嘿,這也是我之前沒有看到的問題:var ref:FIRDatabaseReference!如果你想創建一個根引用,更好的方法是讓rootRef = FIRDatabase.database()。參考() – matthew