arrays - 获取我的 Firebase 数据库的一部分中的所有子键并显示在 TableView 上

标签 arrays swift uitableview firebase firebase-realtime-database

我正在尝试从我的 firebase 数据库中的子键列表创建一个数组。我可以提取数据,将其插入数组,然后将其打印到控制台,但它不会显示在我的 TableView 中。我已确保 tableview 已连接到 Controller 并且单元格匹配。这是我的代码和数据库结构。

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

最佳答案

您需要在完成填充数组后重新加载表的数据,即

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()
        }
    })
}

关于arrays - 获取我的 Firebase 数据库的一部分中的所有子键并显示在 TableView 上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42677658/

相关文章:

PHP 使用数组中的值切换大小写

javascript - 在 JavaScript 中拼接字符串索引数组

swift - 为什么我不能创建一个名为 '!' 的后缀运算符

uitableview - 在 UITableView 的单元格上创建 iOS 7 风格的模糊

ios - 如何在用户点击 Ui 按钮时将相关数据加载到表中?

c++ - 通过指针将多数组传递给函数

C++ 数组调整大小崩溃

ios - 如果连接了 Socket.io,Alamofire 请求总是失败并返回 "The request timed out"

swift - 使用 RealmSwift 创建密码,尝试调用 RealmSwift 函数

ios - UITableView 分隔符奇怪的行为