TableView没有显示来自firebase的数据,但是在" po snapshot"调试控制台显示获取数据

时间:2017-10-21 05:00:45

标签: ios swift firebase firebase-realtime-database

[The Table View is not showing any values that were defined in firebase.][1]

[Firebase已连接。当我在调试控制台中执行Print对象时,正在获取已定义的数据]

https://i.stack.imgur.com/cZuKb.png

**请随意组织和排序,我真的很新。     谢谢 **     //导入

  

import UIKit
import Firebase
import FirebaseDatabase

class DatabaseViewController: UIViewController, UITableViewDelegate, 
UITableViewDataSource {
override func viewDidLoad() {
    // Do any additional setup after loading the view.
    //Firebase Refernece
    ref = FIRDatabase.database().reference()
    databaseHandle = ref?.child("CandleInventory").observe(.childAdded,  
with: { (snapshot) in
        //Execute Snapshot
        let candle = snapshot.value as! String?
        if let actualCandle = candle {
            self.candleData.append(actualCandle)

                    }
    })

    tableView.reloadData()
}

@IBOutlet weak var tableView: UITableView!

var ref: FIRDatabaseReference!
var databaseHandle:FIRDatabaseHandle?

var candleData = [String]()


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

public func tableView(_ tableView: UITableView, numberOfRowsInSection 
section: Int) -> Int {
    return candleData.count
}

public func tableView(_ tableView: UITableView, cellForRowAt indexPath: 
IndexPath) -> UITableViewCell {
    let cell = UITableViewCell(style: UITableViewCellStyle.default, 
reuseIdentifier: "cell")
    cell.textLabel?.text = candleData[indexPath.row]

    return(cell)
}


//Datajust wont output


}

3 个答案:

答案 0 :(得分:2)

我很确定你想从观察者那里重新加载数据,就是数据被追加之后:

databaseHandle = ref?.child("CandleInventory").observe(
   .childAdded,  
   with: { [weak self] (snapshot) in
       guard let `self` = self else { return }

       let candle = snapshot.value as! String?
       guard let actualCandle = candle else { return }

       self.candleData.append(actualCandle)

       DispatchQueue.main.async {
          self.tableView.reloadData() 
       }
   }
)

答案 1 :(得分:1)

要记住的几点 - :

1)确保将Data SourceDelegate提供给表格视图。

2)从数据库或服务器执行一些提取请求,请确保  在主线程上重新加载表。

3)在表格中使用可重复使用的单元格,以节省内存。

4)切勿将代码放在 viewDidLoad()中。制作单独的函数并在此函数中调用它们。

5)确保你也给出了正确的表格cell identifier

6)确保在数组中获得count值。

7)保持代码整洁干净,以便更好地理解。

正如您所说,您可以使用print语句查看值,还要确保它们附加在数组中,并且只是在主线程上重新加载表。

代码 - :

import UIKit
import Firebase
import FirebaseDatabase

class DatabaseViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

 // OUTLETS AND VARIABLES

    @IBOutlet weak var tableView : UITableView!
    var ref                      : FIRDatabaseReference!
    var databaseHandle           :FIRDatabaseHandle?

    var candleData               = [String]()


   //MARK-: viewDidLoad()

     override func viewDidLoad() {
     super.viewDidLoad()
  // CALL FUNCTION HERE
    fetchResultFromFirebase()
   }

  // didReceiveMemoryWarning()

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

   // FUNCTION TO CONNECT FIREBASE AND GET VALUES

    func fetchResultFromFirebase(){

   // FETCH DATA FROM FIREBASE

    ref = FIRDatabase.database().reference()
    databaseHandle = ref?.child("CandleInventory").observe(.childAdded, 
    with: { [weak self] (snapshot) in
        //Execute Snapshot
        let candle = snapshot.value as! String?
        if let actualCandle = candle {

       // MAKE SURE VALUE IS APPENDED

        self.candleData.append(actualCandle) }
    })

   // RELOAD UI STUFF ON MAIN THREAD

   DispatchQueue.main.async {
    self.tableView.reloadData()
  }

}

// TABLE VIEW numberOfRowsInSection

   public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return candleData.count
   }

// ALWAYS USE REUSABLE CELLS

  public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

   let cell = tableView.dequeueReusableCell(withIdentifier: "CellComment", for: indexPath )

    cell.textLabel?.text = candleData[indexPath.row]

    return cell
 }

}

答案 2 :(得分:0)

非常简单的修复。我为你添加了一些错误处理,如果你不介意的话,我会稍微清理一下。我不知道您是否需要为您的程序使用.observe,但请确保最终删除此侦听器或使用observeSingleEvent(of: .childAdded)仅获取一次。如果此代码在第一轮中没有产生任何内容,那么您可能需要使用singleEvent .value,然后使用.childAdded事件使用observer。如果您需要更多帮助,请告诉我。

@objc func firebaseCall(completionHandler: @escaping (Bool) -> ()){
     ref = FIRDatabase.database().reference()
    databaseHandle = ref?.child("CandleInventory").observe(.childAdded,  
with: { (snapshot) in
        if snapshot.value is NSNull{
            //Handle errors
            completionHandler(false)
            return
        }
        else{
            //Execute Snapshot
            if let candle = snapshot.value as? String{
                self.candleData.append(actualCandle)
                completionHandler(true)
            }
            else{
                completionHandler(false)
            }
        }
    })
}


override func viewDidLoad(){
     super.viewDidLoad()
     firebaseCall() { result in
          if result{
              self.tableView.reloadData()
          }
          else{
              //No data found
          }
     }
}