我的viewDidLoad函数中有一个observeSingleEvent,我想将它改为observeswith.childAdded,这样它将不断侦听,并在对象添加到数据库时添加它们。
下面是从firebase读取的代码:
let parentRef = Database.database().reference().child("Recipes")
parentRef.observeSingleEvent(of: .value, with: { snapshot in
// PROCESSES VALUES RECEIVED FROM SERVER
if ( snapshot.value is NSNull ) {
// DATA WAS NOT FOUND
print("– – – Data was not found – – –")
} else {
// DATA WAS FOUND
for user_child in (snapshot.children) {
let user_snap = user_child as! DataSnapshot
let dict = user_snap.value as! [String: String?]
// DEFINE VARIABLES FOR LABELS
let recipeName = dict["Name"] as? String
let recipeDescription = dict["Description"] as? String
food.append(Element(name: recipeName!, description: recipeDescription!))
self.tableView.reloadData()
}
}
})
我现在的另一个问题(除了它只加载一次)是,每当我转到应用程序中的另一个视图,然后回来时,它会再次读取所有内容,这样我的tableView中的所有内容都会重复,这种情况还会发生吗?
编辑:
以下是我的数据库:
Recipes
-Kv7FAqgLtDrRoyGd-99
Description: "food description"
Name: "food name"
-KvBuzMUnIQXn8gpG2WL
Description: "food description2"
Name: "food name2"
-KvH6yYeJaThK7oP8xBj
Description: "food description3"
Name: "food name3"
最佳答案
将observeSingleEvent更改为observe。
观察新值时清空食物数组。
在for循环外重新加载食物数组,以便仅在将所有项目加载到数组中时才重新加载。
let parentRef = Database.database().reference().child("Recipes")
// 1. Change to observe
parentRef.observe(.value, with: { snapshot in
// PROCESSES VALUES RECEIVED FROM SERVER
if ( snapshot.value is NSNull ) {
// DATA WAS NOT FOUND
print("– – – Data was not found – – –")
} else {
// 2. Empty food array
self.food = []
// DATA WAS FOUND
for user_child in (snapshot.children) {
let user_snap = user_child as! DataSnapshot
let dict = user_snap.value as! [String: String?]
// DEFINE VARIABLES FOR LABELS
let recipeName = dict["Name"] as? String
let recipeDescription = dict["Description"] as? String
food.append(Element(name: recipeName!, description: recipeDescription!))
}
// 3. reload tableview outside loop
self.tableView.reloadData()
}
})
通过在观察新值时清空食物数组,可以确保只显示数据库中存在的值,因此不会有重复的元素。