【发布时间】:2020-01-16 09:03:23
【问题描述】:
我无法理解如何实现侦听器,以便我可以观察数据库中的变化并将它们实时反映到表视图中。我想观察 isOnline 和 isHorizontal 的变化,根据该变化我将更改标签值以及图像值。这是我的代码:
var userInfoArray : [UserModel] = [UserModel]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
// readData()
tableView.dataSource = self
tableView.delegate = self
self.tableView.rowHeight = 70
retrieveUserInfo()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// print(emailModified.count)
return userInfoArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "tableViewCell", for: indexPath) as! TableViewCell
cell.userLbl.text = "User \([userInfoArray[indexPath.row].email].count)"
if userInfoArray[indexPath.row].isHorizontal == true {
cell.messageLbl.text = "I am Horizontal"
} else {
cell.messageLbl.text = ""
}
if userInfoArray[indexPath.row].isOnline == true {
cell.onlineImage.image = UIImage(named: "online")
}else {
cell.onlineImage.image = UIImage(named: "offline")
}
return cell
}
func retrieveUserInfo() {
Database.database().reference().child("new user").observeSingleEvent(of: .value) { (snapshot) in
for child in snapshot.children.allObjects as! [DataSnapshot] {
print(child.children)
// this will iterate through all children in snapshot at at path specified.
if let userList = child.value as? Dictionary <String,Any> {
let email = userList["email"]
print(email)
let onlineStatus = userList["isOnline"] as! Any
let horizontalStatus = userList["isHorizontal"] as! Any
let list = UserModel()
list.email = email as? String ?? "nil"
print(list.email)
list.isHorizontal = horizontalStatus as! Bool
list.isOnline = onlineStatus as! Bool
self.userInfoArray.append(list)
print(self.userInfoArray)
}
self.tableView.reloadData()
}
}
【问题讨论】:
标签: ios swift firebase firebase-realtime-database