迭代Firebase中节点中的所有节点

时间:2017-02-07 21:31:21

标签: ios uitableview firebase swift3 firebase-realtime-database

我的样本结构如下所示: enter image description here

我想将每个项目添加到我创建的项目数组中。因此,您可以看到downloadListData函数只能从Apples下载信息,因为我不知道如何在不编写大量代码的情况下同时获取Apples,Bread和Eggs。我正在尝试循环和数组,但它没有用。更多我在网上分析的例子,我没有得到在我的应用程序中有效的答案。

ListItem.swift:

import Foundation
import Firebase

struct ListItem{
    var name : String!
    var addedBy : String!
    var completed : Bool!

    init(name: String, addedBy: String, completed: Bool){
        self.name = name
        self.addedBy = addedBy
        self.completed = completed
    }
}

我的ViewController.swift的一部分:

import UIKit
import Firebase

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    var rootRef : FIRDatabaseReference!
    var listDataRef : FIRDatabaseReference!

    var refHandle: UInt!

    var listItemsDownload = [ListItem]()

    //test vars
    var user : String!

    @IBOutlet weak var plusButton: UIButton!
    @IBOutlet weak var tableView: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        tableView.delegate = self
        tableView.dataSource = self
        user = "test@me.com"


        rootRef = FIRDatabase.database().reference()
        listDataRef = rootRef.child("listData")            

        downloadListData()
    }

func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

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

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as? CellData{

        print("cellForRowAt")
        let items = listItemsDownload[indexPath.row]
        // testing the tableView            
        cell.nameLabel?.text = items.name

        }
        return cell
    } else{
        print("else")
        return CellData()
    }
}
func downloadListData(){
    print(" ### DOWNLOAD ###")
    self.listDataRef.observe(FIRDataEventType.value, with: { snapshot in
        var downloadedName : String!
        var downloadedUser : String!
        var downloadedComplete : Bool!

        if let dict = snapshot.value as? Dictionary<String, Any>{
            if let apples = dict["Apples"] as? Dictionary<String, Any>{

                if let name = apples["name"] as? String{
                    downloadedName = name
                }

                if let user = apples["addedBy"] as? String{
                    downloadedUser = user
                }

                if let completed = apples["completed"] as? Bool{
                    downloadedComplete = completed
                }

                let item = ListItem(name: downloadedName, addedBy: downloadedUser, completed: downloadedComplete)

                self.listItemsDownload.append(item)

                self.tableView.reloadData()

            }
        }
    })
}

所以我可能只需更改此行以获得不同的值而不仅仅是苹果(if let apples = dict["Apples"] as? Dictionary<String, Any>{

1 个答案:

答案 0 :(得分:2)

只需使用一个单独的方法,您可以使用不同的键调用,如下所示:

  func downloadListData(){
    print(" ### DOWNLOAD ###")
    self.listDataRef.observe(FIRDataEventType.value, with: { snapshot in
        addAllItemsFromSnapshotWithKey(snapshot, key: "Apples")
        addAllItemsFromSnapshotWithKey(snapshot, key: "Bread")
        addAllItemsFromSnapshotWithKey(snapshot, key: "Eggs")
        // You need to reload your table view on the main thread, since it's an asynchronous call to firebase
        DispatchQueue.main.async {
          self.tableView.reloadData()  
        }
    })
  }

  func addAllItemsFromSnapshotWithKey(_ snapshot: FIRDataSnapshot, key: String) {
    var downloadedName : String!
    var downloadedUser : String!
    var downloadedComplete : Bool!

    if let dict = snapshot.value as? Dictionary<String, Any>{
      if let values = dict[key] as? Dictionary<String, Any> {

        if let name = values["name"] as? String{
          downloadedName = name
        }

        if let user = values["addedBy"] as? String{
          downloadedUser = user
        }

        if let completed = values["completed"] as? Bool{
          downloadedComplete = completed
        }

        let item = ListItem(name: downloadedName, addedBy: downloadedUser, completed: downloadedComplete)

        self.listItemsDownload.append(item)

      }
    }
  }

更新可扩展的解决方案。只需遍历所有键

 func downloadListData(){
    print(" ### DOWNLOAD ###")
    self.listDataRef.observe(FIRDataEventType.value, with: { snapshot in
      var downloadedName : String!
      var downloadedUser : String!
      var downloadedComplete : Bool!

      if let dict = snapshot.value as? Dictionary<String, Any>{

        for key in dict.keys {

          if let values = dict[key] as? Dictionary<String, Any> {

            if let name = values["name"] as? String{
              downloadedName = name
            }

            if let user = values["addedBy"] as? String{
              downloadedUser = user
            }

            if let completed = values["completed"] as? Bool{
              downloadedComplete = completed
            }

            let item = ListItem(name: downloadedName, addedBy: downloadedUser, completed: downloadedComplete)

            self.listItemsDownload.append(item)
          }
        }
        DispatchQueue.main.async {
          self.tableView.reloadData()
        }
      }
    })
  }