Read data from firebase and populate TableViewCell

主宰稳场 提交于 2019-12-04 15:21:05

Assuming your database layout should instead look like this (see comments above):

...
placeLabel
    |
    -- XXY: "Veranda"
    -- YYY: "Dio Con Dio"
rating
    |
    -- XXX: 4
    -- YYY: 1
...   

then try this:

private func loadData() {
    dbRef!.child("placeLabel").observe(.childAdded) { 
        (snapshot) in
        let label = snapshot.value as! String
        self.updatePlace(snapshot.key, label: label)
     }
     dbRef!.child("rating").observe(.childAdded) { 
        (snapshot) in
        let rating = snapshot.value as! Int
        self.updatePlace(snapshot.key, rating: rating)
     }
}

private var loadedLabels = [String: String]()
private var loadedRatings = [String: Int]()

private func updatePlace(_ key: String, label: String? = nil, rating: Int? = nil) {
    if let label = label { 
        loadedLabels[key] = label
    } 
    if let rating = rating { 
        loadedRatings[key] = rating
    }
    guard let label = loadedLabels[key], let rating = loadedRatings[key] else {
        return 
    }  
    if let place = Places(name: label, rating: rating) {
        places.append(place)
        placesTableView.reloadData()
    }
}

By the way, you can temporarily hack your database — using Firebase (nice!) web console — if you want to quickly validate the above solution.


Writing to Database. Try the following code to write the nodes in your database (i.e., this code reuses the same key across all place properties):

let key = dbRef!.child("placeLabel").childByAutoId().key

dbRef!.child("placeLabel").child(key).setValue(placeLab‌​el.text)
dbRef!.child("comment").child(key).setValue(commentText‌​Field.text) 
dbRef!.child("rating").child(key).setValue(ratingContro‌​l.rating)

Hacking the Database. To edit the database manually, try:

  1. open http://console.firebase.google.com
  2. select your app
  3. open database option
  4. add a new node with the right key
  5. delete the old node
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!