如何在Firebase数据库xcode 9中更新应用程序本身中的现有数据?

时间:2019-01-18 09:35:17

标签: swift xcode firebase firebase-realtime-database tableview

我有一个表视图控制器,可加载用户的Firebase数据。当我单击一个单元格时,将出现一个EditViewController,其中传递了用于填充给定文本字段,标签等的数据。但是,当我单击“保存”按钮时,它会引发错误,因为没有保存任何数据,因此没有数据被表视图控制器获取。如何将现有数据更新到同一棵树?

func editedRecipe() {

    let key = refRecipe.childByAutoId().key
    let recipe = ["id" : key,
                  "name" : nameTextField.text!,
                  "rating" : ratingControl.rating] as [String : Any]        
        self.refRecipe.child((FIRAuth.auth()?.currentUser?.uid)!).child(key).setValue(recipe)
}

这是我的Firebase树结构(概述):

->recipes
   ->id of the user
         ->recipe id
              ->recipename
              ->reciperating

我需要在配方的现有树形结构上编辑和更新配方数据,但此刻应用程序崩溃了。

这是尝试将数据加载回表视图时的错误:

    func loadData() {
    refRecipes.child((user?.uid)!).observe(FIRDataEventType.value, with: { (snapshot) in
        // If the reference have some values
        if snapshot.childrenCount > 0 {

            // Clearing list
            self.recipeList.removeAll()

            // Iterating through all values
            for recipe in snapshot.children.allObjects as! [FIRDataSnapshot] {

                let recipeObject = recipe.value as? [NSString: AnyObject]
                let recipeID = recipeObject?["id"]
                let recipeName  = recipeObject?["name"]
                let recipeRating = recipeObject?["rating"]

                // Fetching
                let recipe = Recipe(id: recipeID as! String, name: recipeName as! String, rating: recipeRating as! Int) --> ERROR HERE: Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value

                // Appending to list
                self.recipeList.append(recipe!)
            }
            // Reloading tableview
            self.tableView.reloadData()
        }
    })
}

0 个答案:

没有答案