我正在尝试从我的firebase数据库中的子键列表中创建一个数组。我可以拉取数据,将其插入到数组中,然后将其打印到控制台,但它不会显示在我的表视图中。我确保tableview连接到控制器并且单元格匹配。这是我的代码和数据库结构。
import UIKit
import Firebase
import FirebaseDatabase
class TeamDataSegueViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var ageListTable: UITableView!
let ref = FIRDatabase.database().reference()
var ageList = [String]()
override func viewDidLoad() {
super.viewDidLoad()
dataObserver()
self.ageListTable.delegate = self
self.ageListTable.dataSource = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func dataObserver() {
ref.child("Database").observeSingleEvent(of: .value, with: { (snapshot) in
for child in snapshot.children {
let snap = child as! FIRDataSnapshot
self.ageList.append(snap.key)
print(self.ageList)
print(snap.key)
}
})
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return ageList.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = ageListTable.dequeueReusableCell(withIdentifier: "cell")
cell?.textLabel?.text = ageList[indexPath.row]
return cell!
}
}
我无法弄清楚如何展示它,但这几乎就是它。我希望能够接受所有年龄组并将其列在tableview中,即age_group1,age_group2。
- 504
- Database
- age_group1
- count
- age_group2
- count
答案 0 :(得分:1)
完成数组填充后,您需要重新加载表的数据,即
func dataObserver() {
ref.child("Database").observeSingleEvent(of: .value, with: { (snapshot) in
for child in snapshot.children {
let snap = child as! FIRDataSnapshot
self.ageList.append(snap.key)
print(self.ageList)
print(snap.key)
self.ageListTable.reloadData()
}
})
}
答案 1 :(得分:0)
最简单的方法是将每个快照转换为字典,并将值拉出,如下所示:
for child in snapshot.children {
let snap = child as! FIRDataSnapshot
if let childDic = FIRSnap.value as? Dictionary<String, AnyObject> {
//do something with this dictionary
}
self.ageList.append(snap.key)
print(self.ageList)
print(snap.key)
}