Firebase 快照未被强制转换为字典



我有这个函数,应该从Firebase的comments node中获取数据。我想实现分页以不一次加载 100+ 条评论。一切似乎都在工作,但我的代码似乎无法将snapchat.value转换为Dictionary

func fetchComments(){
messagesRef = Database.database().reference().child("Comments").child(eventKey)
var query = messagesRef?.queryOrderedByKey()
if comments.count > 0 {
let value =  comments.last?.commentID
query = query?.queryStarting(atValue: value)
}
query?.queryLimited(toFirst: 2).observe(.childAdded, with: { (snapshot) in
var allObjects = snapshot.children.allObjects as? [DataSnapshot]
allObjects?.forEach({ (snapshot) in
// print out snapshot and it isn't empty 
print(snapshot.value) // here it keeps going into the else statement even though snapshot.value clearly exist.
guard let commentDictionary = snapshot.value as? [String:Any] else{
return
}
print(commentDictionary)
})
}) { (err) in
print("Failed to observe comments")
}
}

我的问题是,任何人都可以看看这个,也许看看我哪里出错了?我的代码对我来说看起来不错,我看不出出了什么问题。

我的树看起来像这样

"Comments" : {
"CCDS" : {
"-KrrsXkj6FznzRD0-Xzs" : {
"content" : "Shawn",
"profileImageURL" : "https://firebasestorage.googleapis.com/v0/b/eventful-3d558.appspot.com/o/profile_images%2FBC868F8F-E9EC-4B9D-A248-DD2187BC140C.PNG?alt=media&token=fb14700c-2b05-4077-b45c-afd3de705801",
"timestamp" : 1.503102381340935E9,
"uid" : "oxgjbrhingbf7vbaHpflhw6G7tB2"
}
},
"MIA" : {
"-Krghz9d5_CPjkmdffef" : {
"content" : "22",
"profileImageURL" : "https://firebasestorage.googleapis.com/v0/b/eventful-3d558.appspot.com/o/profile_images%2FF50F6915-DEAB-4A5B-B1AB-CABC1E349148.PNG?alt=media&token=4eb7c708-ec87-45bf-952d-0bd410faee50",
"timestamp" : 1.502915064803007E9,
"uid" : "oxgjbrhingbf7vbaHpflhw6G7tB2"
},
"-KrpoEnNYsmRZ5guORUj" : {
"content" : "23",
"profileImageURL" : "https://firebasestorage.googleapis.com/v0/b/eventful-3d558.appspot.com/o/profile_images%2FBC868F8F-E9EC-4B9D-A248-DD2187BC140C.PNG?alt=media&token=fb14700c-2b05-4077-b45c-afd3de705801",
"timestamp" : 1.503067700479352E9,
"uid" : "oxgjbrhingbf7vbaHpflhw6G7tB2"
}
}
}

根据我的代码,它绕过了密钥并直接转到了子级。 例如,如果传入MIA,它应该转到MIA并获取与每个注释"-KrrsXkj6FznzRD0-Xzs"和"-KrpoEnNYsmRZ5guORUj"相对应的键,但它返回该唯一ID下的所有内容。这是一个问题

回调中的代码似乎假定您被调用了一组注释。要获得这样的集合,您需要观察.value事件。当您观察.value事件时,将使用包含与查询匹配的所有节点的单个snapshot调用回调:

query?.queryLimited(toFirst: 2).observe(.value, with: { (snapshot) in
var allObjects = snapshot.children.allObjects as? [DataSnapshot]
allObjects?.forEach({ (snapshot) in
print(snapshot.key)
print(snapshot.value)
guard let commentDictionary = snapshot.value as? [String:Any] else{
return
}
print(commentDictionary)
})
}) { (err) in
print("Failed to observe comments")
}

当您观察.childAdded时,会为与查询匹配的每个节点调用回调。这意味着你需要摆脱代码中的循环:

query?.queryLimited(toFirst: 2).observe(.childAdded, with: { (snapshot) in
print(snapshot.key)
print(snapshot.value)
guard let commentDictionary = snapshot.value as? [String:Any] else{
return
}
print(commentDictionary)
}) { (err) in
print("Failed to observe comments")
}