firebase Databse Query Swift没有阅读
问题描述:
并感谢您的帮助!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是唯一的,但我不知道该怎么做......你能告诉我我做错了什么,以及我需要做些什么来获得存储答案出来的数据库为登录用户的
让我知道如果你再
由于需要任何进一步澄清的时间和帮助
答
的问题是,您要查询的答案结点,而不是用户,对于具有键“答案”的子节点,您的帖子似乎并不存在,除非您在答案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)
})
感谢您在百忙之中阅读我的文章的时候了!很好的解释,这是有道理的......不幸的是没有任何东西被印在领事!任何其他建议?你确定我的代码与userId是正确的吗?任何其他建议如何处理使用唯一的ID? – theGuiza
你有数据结构的方式将工作。驱动程序问题的节点,随机UID密钥以及该节点的数据。我更新了我的答案,以获取所有用户数据,而不仅仅是传入用户的答案节点中的数据。也许你传递的UID没有答案数据,不会打印任何内容。 – matthew
嘿,这也是我之前没有看到的问题:var ref:FIRDatabaseReference!如果你想创建一个根引用,更好的方法是让rootRef = FIRDatabase.database()。参考() – matthew