将观察值转换为swift中的.childAdded

目前我遇到了一些代码的问题,从firebase数据库加载数据到数组中。 因为这是在viewDidLoad里面,我必须清空我的数组food = []之前加载数据,如果我不这样做,那么它会复制所有的对象,我会有双重复第二次它加载,三倍的第三时间等等…然而,这不是一个很好的解决方法,因为多种原因,所以我想只能使用.childAdded从数据库添加新对象,但是如果我只是用.childAdded切换.value ,它会崩溃,我在这一行得到一个Thread 1: signal SIGABRTlet dict = user_snap.value as! [String: String?] let dict = user_snap.value as! [String: String?] 。 我很新很快,不知道如何解决这个问题,真的很感激一些帮助。

 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> 

也许你可以做空testing:

 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> //..... }