如何从Firebase检索数据到TableViewCell

时间:2016-06-24 10:38:33

标签: ios arrays swift

我正在研究简单程序 - 我创建了产品对象,然后计算他们的卡路里。

我想在TableViewController中获取所有产品

我已经创建了一个方法,允许我在Firebase中正确保存数据,但是在将它们检索到单元格时我遇到了问题。我没有犯错,但我也没有任何结果

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!

    }

这是我的DataService文件:

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)

    }

我无法得到我做错的事。所有产品都表示为字典。

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
        }


    }


}

1 个答案:

答案 0 :(得分:0)

您使用了

var products = [Products]()

但不添加来自firebase回调的任何项目

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

请添加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)
 }