使用使用Firebase填充的阵列填充原型单元格

时间:2017-04-02 03:00:36

标签: swift firebase firebase-realtime-database tableview

如何使用Firebase填充TableView Cell?我正在尝试使用一个由Firebase填充的数组来填充它,但由于数据是异步填充的,我不知道如何使数组填充getData()函数之外的数据。截至目前,数据已在完成处理程序内填充,但除此之外它是零。

import UIKit
import Firebase

class ProxiesListViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

@IBOutlet weak var ProxiesTableView: UITableView!

var proxyname:[String] = []
var proxyprice:[Int] = []
var proxycountry:[String] = []

var databaseRef : FIRDatabaseReference!

func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    // #warning Incomplete implementation, return the number of sections
    return 1
}

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

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

    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! ProxiesTableViewCell
    cell.countryFlag.image = UIImage(named: proxycountry[indexPath.row])
    cell.NameLabel.text = proxyname[indexPath.row]
    cell.priceLabel.text = "$" + String(proxyprice[indexPath.row])
    return(cell)
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    //add code
}

override func viewDidLoad() {
    super.viewDidLoad()

    ProxiesTableView.delegate = self
    ProxiesTableView.dataSource = self

    getData()
}

func getData() {
    databaseRef = FIRDatabase.database().reference()

    /*
     proxyname = ["50 Proxies (24 Hours)", "100 Proxies", "10 Proxies", "60 Proxies (48 Hours)"]
     proxyprice = [600, 140, 60, 10]
     proxycountry = ["CA", "UK", "UK", "US"]
     */

    self.databaseRef.child("ProxiesItemsFeed").observe(.childAdded, with: { (snapshot) in

        if let proxynames = snapshot.key as String! {
            self.proxyname.append(proxynames)   
                self.databaseRef.child("ProxiesItemsFeed").child(proxynames).observe(.childAdded, with: { (snapshot) in

                    if let country = snapshot.key as String! {
                        self.proxycountry.append(country)
                    }

                    if let price = snapshot.value as! Int! {
                        self.proxyprice.append(price)
                    }
                })
            }
        })
    }
}

1 个答案:

答案 0 :(得分:0)

您应该在完成处理程序中添加tableView.reloadData()(即getData()方法中的那个)。

方法文档:

  

调用此方法重新加载用于构造表的所有数据,包括单元格,节页眉和页脚,索引数组等。