admin管理员组

文章数量:1122846

I am having problems with this function:

    func updateUserStatistics(score: Int, totalQuestionsAnswered: Int) async {
        // Checks if there is a user in the session
        guard let uid = userSession?.uid else {
            self.errorMessage = "User not found in session"
            return
        }

        do {
            // Retrieves the user's document reference
            let db = Firestore.firestore()
            let userDataRef = db.collection("userData").document(uid)
            
            // Get the user's data
            let snapshot = try await userDataRef.getDocument()

            // Check whether the data has been retrieved correctly
            guard let userData = try? snapshot.data(as: UserData.self) else {
                self.errorMessage = "Unable to recover user data"
                return
            }

            // Add the new scores and the number of questions
            var updatedUserData = userData
            updatedUserData.statistics.score += score
            updatedUserData.statistics.questionNumber += totalQuestionsAnswered

            // Save the updated data in the Firestore
            let encodedData = try Firestore.Encoder().encode(updatedUserData)
            try await userDataRef.setData(encodedData, merge: true)

            // Success log
            print("Statistics successfully updated")

        } catch {
            // Error handling
            self.errorMessage = "Error when updating statistics: \(error.localizedDescription)"
            print("Errore: \(error.localizedDescription)")
        }
    }

In the view where i have a button to update the stats the action is this:

    private func updateUserStatistic() {
        guard let user = viewModel.currentUser else {
            print("Error: current user not found!")
            return
        }

        Task {
            guard let userData = viewModel.userData else {
                print("Error: user data not found!")
                return
            }

            // Log temporanei
            print("SCurrent statistics in the database:")
            print("Saved score: \(userData.statistics.score)")
            print("Savede question number: \(userData.statistics.questionNumber)")

            let newScore = score + userData.statistics.score
            let newTotalQuestions = totalQuestions + userData.statistics.questionNumber
            print ("Updated score: \(newScore)")
            print ("Updated total questions: \(newTotalQuestions)")

            do {
                await viewModel.updateUserStatistics(score: newScore, totalQuestionsAnswered: newTotalQuestions)
                print("Firebase...")
                print("New statistics in the database:")
                print("Saved sccore: \(userData.statistics.score)")
                print("Saved question number: \(userData.statistics.questionNumber)")
            } catch {
                print("Error while updating statistics: \(error)")
            }
        }
    }

I added several prints in the second function to see if anything was happening. In firestore database i have two db, one for user and one for user data. This is the console output:

Current statistics in the database:
Saved score: 20
Savede question number: 40
Updated score: 26
Updated total questions: 50
Firebase...
New statistics in the database:
Saved sccore: 20
Saved question number: 40

I am having problems with this function:

    func updateUserStatistics(score: Int, totalQuestionsAnswered: Int) async {
        // Checks if there is a user in the session
        guard let uid = userSession?.uid else {
            self.errorMessage = "User not found in session"
            return
        }

        do {
            // Retrieves the user's document reference
            let db = Firestore.firestore()
            let userDataRef = db.collection("userData").document(uid)
            
            // Get the user's data
            let snapshot = try await userDataRef.getDocument()

            // Check whether the data has been retrieved correctly
            guard let userData = try? snapshot.data(as: UserData.self) else {
                self.errorMessage = "Unable to recover user data"
                return
            }

            // Add the new scores and the number of questions
            var updatedUserData = userData
            updatedUserData.statistics.score += score
            updatedUserData.statistics.questionNumber += totalQuestionsAnswered

            // Save the updated data in the Firestore
            let encodedData = try Firestore.Encoder().encode(updatedUserData)
            try await userDataRef.setData(encodedData, merge: true)

            // Success log
            print("Statistics successfully updated")

        } catch {
            // Error handling
            self.errorMessage = "Error when updating statistics: \(error.localizedDescription)"
            print("Errore: \(error.localizedDescription)")
        }
    }

In the view where i have a button to update the stats the action is this:

    private func updateUserStatistic() {
        guard let user = viewModel.currentUser else {
            print("Error: current user not found!")
            return
        }

        Task {
            guard let userData = viewModel.userData else {
                print("Error: user data not found!")
                return
            }

            // Log temporanei
            print("SCurrent statistics in the database:")
            print("Saved score: \(userData.statistics.score)")
            print("Savede question number: \(userData.statistics.questionNumber)")

            let newScore = score + userData.statistics.score
            let newTotalQuestions = totalQuestions + userData.statistics.questionNumber
            print ("Updated score: \(newScore)")
            print ("Updated total questions: \(newTotalQuestions)")

            do {
                await viewModel.updateUserStatistics(score: newScore, totalQuestionsAnswered: newTotalQuestions)
                print("Firebase...")
                print("New statistics in the database:")
                print("Saved sccore: \(userData.statistics.score)")
                print("Saved question number: \(userData.statistics.questionNumber)")
            } catch {
                print("Error while updating statistics: \(error)")
            }
        }
    }

I added several prints in the second function to see if anything was happening. In firestore database i have two db, one for user and one for user data. This is the console output:

Current statistics in the database:
Saved score: 20
Savede question number: 40
Updated score: 26
Updated total questions: 50
Firebase...
New statistics in the database:
Saved sccore: 20
Saved question number: 40
Share Improve this question edited Nov 22, 2024 at 14:23 Doug Stevenson 317k36 gold badges453 silver badges472 bronze badges Recognized by Google Cloud Collective asked Nov 22, 2024 at 13:53 antocirinoantocirino 11 bronze badge
Add a comment  | 

1 Answer 1

Reset to default 0

It doesn't look like you're reloading the userData anywhere after calling updateUserStatistics. To get the updated data from the database, you'll need to call await userDataRef.getDocument() somewhere again.

Note that this happens automatically if you use a realtime listener, rather than explicit get calls.

本文标签: firebaseUpdate data in Firestore Database with SwiftUIStack Overflow