我想從firebase加載一些數據以用於我的ios應用程序,但似乎整個觀察方法沒有得到執行。使用firebase檢索數據不會返回任何內容
這是火力數據:
{
"tips" : {
"Nog een" : {
"category" : "Drinking",
"description" : "Dikke test jooo",
"name" : "Nog een",
"score" : 0
},
"testtip" : {
"category" : "Going Out",
"description" : "reteketet keta pret",
"name" : "testtip",
"score" : 0
}
}
}
這是我的加載代碼:
let tipsRef = Database.database().reference().child("tips")
var tips: [Tip] = []
tipsRef.observe(.value, with: { (snapshot) in
if !snapshot.exists(){
print("not found")
}
else{
for item in snapshot.children{
let tip = Tip(snapshot: item as! DataSnapshot)
tips.append(tip)
}
self.tipsArray = tips
}
})
如果!snapshot.exists(){
線不會被達到。
在同一個類中,我將這些對象插入數據庫,這沒有任何問題。
let tipRef = Database.database().reference(withPath: "tips")
let newTipRef = tipRef.child(newTip.name)
newTipRef.setValue(newTip.toAnyObject())
我不知道爲什麼,這是行不通的,在一個類似的項目幾乎相同的代碼不工作...
UPDATE Nirav D的回答幫我解決這個問題,但現在我需要一個新的初始化爲「提示」,我不知道如何做到這一點。我添加了我正在使用的init。
let tipsRef = Database.database().reference().child("tips")
var tips: [Tip] = []
tipsRef.observe(.value, with: { (snapshot) in
if let dictionary = snapshot.value as? [String:[String:Any]] {
for item in dictionary {
let tip = Tip(dictionary: item)
tips.append(tip)
}
}
self.tipsArray = tips
})
convenience init(snapshot: DataSnapshot){
self.init()
let snapshotValue = snapshot.value as! [String:AnyObject]
self.name = snapshotValue["name"] as! String
self.description = snapshotValue["description"] as! String
self.category = snapshotValue["category"] as! String
self.score = snapshotValue["score"] as! Int
}
你的意思是它正在執行else塊嗎? –
這不是,我更新了我的文章,謝謝 – Sanderoo