将观察 .value 转换为 .child在 swift 中添加



目前,我在使用将数据从Firebase数据库加载到数组中的代码时遇到了一些问题。由于这是在 viewDidLoad 内部,因此在将数据加载到数组中之前,我必须清空我的数组food = [],如果我不这样做,那么它将复制所有对象,第二次加载时我将有双倍重复,第三次重复三倍,依此类推......但是,由于多种原因,这不是一个好的修复方法,因此我想要的是它只会从数据库中添加新对象.childAdded但是如果我只是用.childAdded切换.value它会崩溃,我得到Thread 1: signal SIGABRT在这一行:let dict = user_snap.value as! [String: String?]。我是 swift 的新手,不知道如何解决这个问题,非常感谢一些帮助。

let parentRef = Database.database().reference().child("Recipes")
let storage = Storage.storage()
parentRef.observe(.value, with: { snapshot in
if ( snapshot.value is NSNull ) {
// DATA WAS NOT FOUND
print("– – – Data was not found – – –")
} else {
//Clears array so that it does not load duplicates
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?]
//Defines variables for labels
let recipeName = dict["Name"] as? String
let recipeDescription = dict["Description"] as? String
let downloadURL = dict["Image"] as? String
let storageRef = storage.reference(forURL: downloadURL!)
storageRef.getData(maxSize: 1 * 1024 * 1024) { (data, error) -> Void in
let recipeImage = UIImage(data: data!)
food.append(Element(name: recipeName!, description: recipeDescription!, image: recipeImage!))
self.tableView.reloadData()
}
}
}
})
let dict = user_snap.value as! [String: String?]

而不是

let dict = snapshot.value as! Dictionary<String, String>

也许你可以做空测试:

let dict = snapshot.value as! Dictionary<String, String>
if let recipeName = dict["Name"] as String!, let recipeDescription = dict["Description"] as String!, let downloadURL = dict["Image"] as String! {
let storageRef = storage.reference(forURL: downloadURL)
storageRef.getData(maxSize: 1 * 1024 * 1024) { (data, error) -> Void in
let recipeImage = UIImage(data: data!)
food.append(Element(name: recipeName, description: recipeDescription, image: recipeImage!, downloadURL: downloadURL))
self.tableView.reloadData()                        
}                    
}else {
print("Error! Could not decode data")                    
}

试试这个。它应该工作

for child in snapshot.children.allObjects as! [FIRDataSnapshot] {
let dict = child.value as! Dictionary<String, Any>
//.....
}

最新更新