这是我数据库的结构。我使用uuid将每个事件存储为根节点" events"下的唯一标识符。
events:
uuid:
name: summer festival 2017
site: vegas
participants:
employeeID1: true
employeeID2: true
我有一个UITableview有3列,我希望这个表显示以下数据
Colum1(event name) Column2(site) Column2(# of Participants)
summer festival 2017 vegas 2000
我尝试了这段代码,但它没有成功。请帮忙。
let myRef = ref?.child("events")
myRef?.queryOrdered(byChild: "name").observe(.childAdded, with: { (snapshot) in
for child in snapshot.children {
let snap = child as! DataSnapshot
if let eventName = snap.value["name"] as String {
self.events.append(eventName)
}
}
})
答案 0 :(得分:0)
这是您可以尝试的代码。希望它能帮助你!
//TableView outlet
@IBOutlet weak var namesTable: UITableView!
//Array to save all event Names
var names = [String]()
//Database handler Object
var readData = DatabaseReference()
//I use a separate Dictionary to take snapshot out of handler if required
var postData = [String:AnyObject]()
//make use of serrate function or calling didLoad
override func viewDidLoad() {
super.viewDidLoad()
//Database reference to Fetch Data
readData = Database.database().reference()
//here is a databaseHandler which fetch all events data at once
self.databaseHandler = self.readData.child("events").observe(.value, with: { (snapshot) in
self.postData = ((snapshot.value) as? [String : AnyObject]!)!
//print data to see if you require
//print it to generate loop for required things
print(self.postData)
//make snapshot as [string:anyobject]
if let snapDict = snapshot.value as? [String:AnyObject]{
////here is a loop which will run after you get your snapshot
for each in snapDict{
//you will get all your names in a array all at once
let artistName = each.value["name"] as! String
//use this array to save all event name
self.names.append(artistName)
}
//remove ypur datasource and delegate from Storyboard
//here you can provide datasource and delegate
//if on same controller you have multiple functionality
//write reload table line here with datasource and delegate
self.namesTable.dataSource = self
self.namesTable.delegate = self
}
})
}
TableView代理
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView:UITableView, numberOfRowsInSection section:Int) -> Int
{
return names.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = self.namesTable.dequeueReusableCell(withIdentifier: "Cell")!
cell.textLabel?.text = names[indexPath.row]
return cell
}