简体   繁体   中英

How to retrieve data from Firebase to TableViewCell

I'm working on simple program - I create objects of products and then I count their calories.

I want to get all my product in TableViewController

I've created a method, allowing me to save data properly in Firebase, but I got stuck while retrieving them to cell. I got no mistakes, but I don't have any results as well

import UIKit
import Firebase

class MainTableViewController: UITableViewController {

    var products = [Products]()


    override func viewDidLoad() {
        super.viewDidLoad()

            DataService.dataService.PRODUCT_BASE.observeEventType(.Value, withBlock: { snapshot in

                print(snapshot.value)

                self.products = []

                if let snapshots = snapshot.children.allObjects as? [FIRDataSnapshot] {

                    for snap in snapshots {

                        if let postDictionary = snap.value as? Dictionary<String, AnyObject> {

                            let key = snap.key

                            let product = Products(key: key, dictionary: postDictionary)


                        }
                    }
                }

                self.tableView.reloadData()
        })


    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Table view data source

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }

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


    override func tableView(tableView:UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {


        let cell = tableView.dequeueReusableCellWithIdentifier("ProductCell") as! UITableViewCell?
        let ProductItem = products[indexPath.row]

        cell?.textLabel?.text = ProductItem.productName
        cell?.detailTextLabel?.text = String(ProductItem.productCalories)

        return cell!

    }

This is my DataService file:

import Foundation
import Firebase

let URL_BASE = FIRDatabase.database().reference()

class DataService {

    static let dataService = DataService()

    private var _REF_BASE = URL_BASE
    private var _USER_BASE = URL_BASE.child("users")
    private var _PRODUCЕ_BASE = URL_BASE.child("products")

    var REF_BASE: FIRDatabaseReference {
        return _REF_BASE
    }

    var USER_BASE: FIRDatabaseReference {
        return _USER_BASE
    }

    var PRODUCT_BASE: FIRDatabaseReference {
        return _PRODUCЕ_BASE
    }


    var CURRENT_USER_REF: FIRDatabaseReference {

        let userID = NSUserDefaults.standardUserDefaults().valueForKey("uid") as! String

        let currentUser = URL_BASE.child("users").child(userID)

        return currentUser

    }


    func CreateNewProduct(product: Dictionary<String, AnyObject>) {

        let ProductNewRef = DataService.dataService.PRODUCT_BASE.childByAutoId()

        ProductNewRef.setValue(product)

    }

I can't get what I'm doing wrong. All products are represented as a dictionary.

import Foundation
import Firebase

class Products {

    private var _productName: String!

    private var _productCalories: Int!


    var productName: String {

        return _productName

    }

    var productCalories: Int {

        return _productCalories
    }

    init(key: String, dictionary: Dictionary<String, AnyObject>) {


        if let calories = dictionary["calories"] as? Int {

            self._productCalories = calories
        }

        if let name = dictionary["name"] as? String {

            self._productName = name
        }


    }


}

You intilized the

var products = [Products]()

But not adding any items from firebase callback

if let postDictionary = snap.value as? Dictionary<String, AnyObject> {  
         let key = snap.key 
         let product = Products(key: key, dictionary: postDictionary)
 }

please add self.products.append(product)

if let postDictionary = snap.value as? Dictionary<String, AnyObject> {  
         let key = snap.key 
         let product = Products(key: key, dictionary: postDictionary)
         self.products.append(product)
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM