【发布时间】:2017-02-07 21:31:20
【问题描述】:
我想将每个项目添加到我创建的项目数组中。所以你可以看到downloadListData函数只能从Apples下载信息,因为我不知道如何在不编写大量代码的情况下同时获取Apples、Bread和Eggs。我正在尝试循环和数组,但它没有用。此外,我正在分析 Internet 上的示例,但没有得到适用于我的应用程序的答案。
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()
}
}
})
}
所以我可能只需要更改这一行来获得不同的值,而不仅仅是 Apples (if let apples = dict["Apples"] as? Dictionary<String, Any>{
【问题讨论】:
标签: ios uitableview firebase swift3 firebase-realtime-database