2017-06-02 72 views
1

我想從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 
    } 
+0

你的意思是它正在執行else塊嗎? –

+0

這不是,我更新了我的文章,謝謝 – Sanderoo

回答

0

observe閉幕會稱爲異步意味着,當你得到的響應會叫後者。也可能需要訪問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 
} 
+0

謝謝!這工作!雖然我現在不能使用我的DataSnapshot init ...嘗試使用[String:[String:Any]]構造一個構造函數,但是因爲我在swift中是垃圾,所以似乎無法找到如何執行此操作.. 。 – Sanderoo

+0

@Sanderoo不需要你用init初始化'[String:Any]'用你的舊init編輯你的問題我會建議你如何編寫新的初始化 –

+0

@Sanderoo檢查初始化的編輯答案 –

相關問題