我正在将Firebase数据库与Xcode项目连接。我已成功使用print(snapshot.value)将数据库的快照打印到控制台中。但是,我正在努力将数据快照打印到TableView中。谢谢。
这是我的代码:
import UIKit
import FirebaseDatabase
class ViewController: UITableViewController {
@IBOutlet var cosmos: UITextView!
@IBOutlet var gallonsTXT: UITableView!
@IBOutlet var tables: UITableView!
@IBOutlet var Finale: UILabel!
var ref:DatabaseReference?
var databaseHandle:DatabaseHandle?
var postData = [String]()
override func viewDidLoad() {
super.viewDidLoad()
gallonsTXT.delegate = self
gallonsTXT.dataSource = self
ref = Database.database().reference()
databaseHandle = ref?.child("Total gallons:").observe(.childAdded, with: { (snapshot) in
print(snapshot.value)
let post = snapshot.value as? String
if let actualPost = post {
self.postData.append(actualPost)
self.tableView.reloadData()
}
})
// Do any additional setup after loading the view, typic ally from a nib.
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return postData.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "PostCell")
cell?.textLabel?.text = postData[indexPath.row]
return cell!
}
}
最佳答案
调整视图确实加载到以下内容。您必须声明字典才能正确读取和使用Firebase中的数据。
override func viewDidLoad() {
super.viewDidLoad()
gallonsTXT.delegate = self
gallonsTXT.dataSource = self
ref = Database.database().reference()
databaseHandle = ref?.child("Total gallons:").observe(.childAdded, with: { (snapshot) in
print(snapshot.value)
if let dict = snapshot.value as? [String: Any] {
let post = dict["your data key"] as! String
self.postData.append(actualPost)
self.tableView.reloadData()
}
})
// Do any additional setup after loading the view, typic ally from a nib.
}
如果这不起作用,请在文本字段中强制展开文本,然后查看是否产生nil错误。在
CellForRowAtIndexPath
中