使用firebase检索数据不会返回任何内容

时间:2017-06-02 09:23:47

标签: ios swift firebase firebase-realtime-database

我正在尝试从firebase加载一些数据以在我的ios应用程序中使用,但似乎整个observe方法都没有被执行。

这是关于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
    }

1 个答案:

答案 0 :(得分:0)

关闭observe将调用async意味着当你得到响应时它会调用后者。您也可能需要访问snapshot.value而不是snapshot.children。如果您在tableView中显示此数据,则需要在for循环后重新加载tableView

if let dictionary = snapshot.value as? [String:[String:Any]] {
    for item in dictionary {
        let tip = Tip(dictionary: item.value)
        tips.append(tip)
    }
    //Reload your table here
    self.tableView.reloadData()
}

init课程中制作一个Tip,如下所示。

init(dictionary: [String:Any]) {
    self.name = dictionary["name"] as! String
    self.description = dictionary["description"] as! String
    self.category = dictionary["category"] as! String
    self.score = dictionary["score"] as! Int
}