Read data from firebase and populate TableViewCell

雨燕双飞 提交于 2020-01-13 06:08:10

问题


Hello I have a tableviewcell where i can populate it with custom data from my pc, but i can't use my firebase data on the cell that i have made. I want to fill my cell with String and Int, not only Strings. My code is:

PlacesTableViewController Class

import UIKit
import FirebaseDatabase

class PlacesTableViewController: UITableViewController {

    //MARK: Properties
    @IBOutlet weak var placesTableView: UITableView!

    //database reference
    var dbRef:FIRDatabaseReference?

    var places = [Places]()

    var myList:[String] = []

    //handler
    var handle:FIRDatabaseHandle?

    override func viewDidLoad() {
        super.viewDidLoad()

        dbRef = FIRDatabase.database().reference()

        // Loads data to cell.
        loadData()
    }
 // MARK: - Table view data source

    override func numberOfSections(in tableView: UITableView) -> Int {

        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return places.count
        //return myList.count
    }


    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        // Table view cells are reused and should be dequeued using a cell identifier.
        let cellIdentifier = "PlacesTableViewCell"

        guard let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as? PlacesTableViewCell  else {
            fatalError("The dequeued cell is not an instance of PlacesTableView Cell.")
        }

        let place = places[indexPath.row]

        cell.placeLabel.text = place.name
        cell.ratingControl.rating = place.rating

        //cell.placeLabel.text = myList[indexPath.row]
        //cell.ratingControl.rating = myRatings[indexPath.row]

        return cell

    }
//MARK: Private Methods

    private func loadData() {


        handle = dbRef?.child("placeLabel").observe(.childAdded, with: { (snapshot) in
            if let item = snapshot.value as? String
            {
                self.myList.append(item)
                self.placesTableView.reloadData()
                print (item)
            }
        })
/* handle = dbRef?.child("rating").observe(.childAdded, with: { (snapshot) in
            if let item = snapshot.value as? String
            {
                self.myList.append(item)
                self.placesTableView.reloadData()

            }
        })*/
/*guard let place1 = Places(name: "Veranda", rating: 4) else {
            fatalError("Unable to instantiate place1")

        }
        places += [place1]*/

    }

}

Places Class

import UIKit

class Places {

    //MARK: Properties

    var name: String
    var rating: Int

    //MARK:Types

    struct PropertyKey {
        static let name = "name"
        static let rating = "rating"
    }

    //MARK: Initialization

    init?(name: String, rating: Int) {
        // Initialize stored properties.
        self.name = name
        self.rating = rating

        // Initialization should fail if there is no name or if the rating is negative.
        // The name must not be empty
        guard !name.isEmpty else {
            return nil
        }

        // The rating must be between 0 and 5 inclusively
        guard (rating >= 0) && (rating <= 5) else {
            return nil
        }

    }

}

PlacesTableViewCell Class

import UIKit
import FirebaseDatabase

class PlacesTableViewCell: UITableViewCell, UITableViewDelegate {

    //MARK: Properties
    @IBOutlet weak var placeLabel: UILabel!
    @IBOutlet weak var ratingControl: RatingControl!

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

}

Firebase Database


回答1:


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


来源:https://stackoverflow.com/questions/43954708/read-data-from-firebase-and-populate-tableviewcell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!