Magenta Magenta - 9 months ago 238
iOS Question

Swift: Can't synchronize data to table view using Firebase

I was working on a grocery list app. When I tried to synchronise data to table view using Firebase, the grocery item can not be shown on the table view. However, when I reset the simulator, items added before can be shown on the table view, but when I add another item, it can't be shown on the table view. I double checked the code and found nothing wrong. Could you help me fix it?(e.g. In the following two images, the coffee item can not be shown)

Part of code in GroceryListViewController.swift

override func viewDidAppear(animated: Bool) {
//Attach a listener to receive updates.
ref.observeSingleEventOfType(.Value, withBlock: { (snapshot) in

var newItems = [GroceryItem]()

for item in snapshot.children
let groceryItem = GroceryItem(snapshot: item as! FDataSnapshot)
self.items = newItems

Simulator Image
Firebase Image


1 - You are using observeSingleEventOfType (* This is equivalent to observeEventType:withBlock:, except the block is immediately canceled after the initial data is returned.) From the doc. So your listener is called once and stop listening. Use observeEventType instead

2 - You should do the reloadData of your tableview on the main thread like this :


The reason is that you cannot / must not interact with UI from a background thread. Since Firebase is asynchronous the completion block is on a background thread