Firebase不返回数据



我有以下快速代码从Firebase实时数据库检索数据:

private let db = Database.database().reference(withPath: "food")
func fetchFoods() {
db.getData(completion: { error, snapshot in
guard error == nil else {
print("ERROR")
print(error!.localizedDescription)
return
}
print(snapshot.value as? String ?? "Unknown")
// Food data is stored as a map of UUIDs to Food objects
guard let foodDicts = snapshot.value as? [String: Any] else {
print("ERROR: type cast failed")
return
}
})
}

但我有一个奇怪的问题,如果我的数据存储如下:

{
"food": [{
"id": "8466A419-AE6E-4997-BE74-220B59C95F96",
"cholestrol": 0,
"macroProfile": {
"carbProfile": {
"sugar": 0,
"fiber": 0
},
...
}]
}

检索数据没有问题。但是,如果数据是这样存储的:

{
"food": {
"8466A419-AE6E-4997-BE74-220B59C95F96": {
"cholestrol": 0,
"macroProfile": {
"carbProfile": {
"sugar": 0,
"fiber": 0
},
...
}
}
}

我得到了:

Unable to get latest value for query FQuerySpec (path: /, params: {
}), client offline with no active listeners and no matching disk cache entries

我通过编辑database.rules.json并将读写规则设置为true来解决这个问题。

{
"rules": {
".read": true,
".write": true
}
}

你可能会问,为什么另一种数据格式可以工作呢?因为它是从以前缓存的!!在这个过程中,我的规则文件被修改了。

最新更新