SwiftUI:尝试根据用户输入更新 Firebase Realtime Database 中的值,获取新引用,而不是所选统计信息的更新引用

SwiftUI: Trying to update values in Firebase Realtime Database from user input, getting new reference instead of updated reference of selected stat

提问人:a.nguy1 提问时间:11/11/2023 更新时间:11/11/2023 访问量:19

问:

我正在尝试获取我的 Firebase 数据来编辑统计信息。我可以在 EditStatView 中编辑数据,但它最终会在数据库中创建一个新的参考统计信息,而不是编辑我选择的统计信息的值。我相信我错误地分配了子引用值,但不确定如何正确提取我需要的实际引用数据的统计键。任何帮助将不胜感激。

import SwiftUI

struct EditStatView: View {
    var stat: Stat
    var onEditComplete: () -> Void
    var viewModel: StatsViewModel
    
    @State private var editedTitle: String = ""
    @State private var editedValue: String = ""
    @State private var goalType: String
    
    init(stat: Stat, onEditComplete: @escaping () -> Void, viewModel: StatsViewModel){
        self.stat = stat
        self.onEditComplete = onEditComplete
        self.viewModel = viewModel
        
        // Intialize the state variables
            _editedTitle = State(initialValue: stat.title)
            _editedValue = State(initialValue: stat.value)
            _goalType = State(initialValue: stat.goalType)
        
        print("Initializing EditStatView with stat: \(stat)")
    }
    
    var body: some View {
        NavigationView{
            Form {
                Section(header: Text("Edit Stat Details")) {
                    TextField("Category", text: $goalType)
                    TextField("Title", text: $editedTitle)
                    TextField("Value", text: $editedValue)
                } .navigationTitle("Edit \(goalType) Stat")
                Button("Save") {
                    viewModel.editStat(statKey: stat.id.uuidString, title: editedTitle, value: editedValue, goalType: goalType)
                    //self.showing = false
                    onEditComplete()
                }
            }
            .navigationBarItems(leading: Button("Cancel"){ /* action */ })
         }
         .onAppear {
             print("EditStatView appeared with stat: \(stat)")
         }
     }
 }

下面是 editStat 函数:

func editStat(statKey: String, title: String, value: String, goalType: String) {
    guard let uid = Auth.auth().currentUser?.uid else {return}
    
    // Reference the existing stat using the provided key
    let existingStatRef = dbRef.child(uid).child(statKey)
    let updatedStatInfo: [String: Any] = ["title": title, "value": value, "goalType": goalType]
    
    print("Updating stat at path: \(existingStatRef.url)")
    
    existingStatRef.setValue(updatedStatInfo) {(error, _) in
        if let error = error {
            print("Failed to update stat: ", error.localizedDescription)
            return
        }
        
        DispatchQueue.main.async {
            // Update the local data model to reflect the change
            if let index = self.stats.firstIndex(where: {$0.id.uuidString == statKey }) {
                
                // Replace the old stat with the updated stat in the array
                //self.stats[index] = statToUpdate
                self.stats[index].title = title
                self.stats[index].value = value
                self.stats[index].goalType = goalType
                
            }
        }
    }
swift firebase firebase-realtime-database swiftui

评论

0赞 Jay 11/12/2023
不确定是否有足够的信息进行故障排除。使用现有统计信息实例化(我们假设)。该模型似乎包含定义为 ?我建议在代码中添加一个断点并遵循 var - 它什么时候更改?这是什么?请进行一些额外的故障排除并找到失败的代码行 - 然后更新问题。另外,为什么你会这样,因为你没有在UI上做任何事情?EditStatViewStatidUUIDstat.idlet existingStatRef = dbRef.child(uid).child(statKey)DispatchQueue.main.async

答: 暂无答案