How to update userdefaults in another viewController once it is saved in a different viewController without overwriting the first one

58 views Asked by At

This is my User struct.

struct User: Codable {
    let uid: String?
    let name: String?
    var profileImageUrl: String?
    var bookmarkedRecipes: [String]?  // This could be an array of recipe IDs.
}

This is where I save name and uid properties

func signUpCompleted() {
    guard let email = signUpVC?.eMailField.text, !email.isEmpty,
          let password = signUpVC?.passwordField.text, !password.isEmpty,
          let name = signUpVC?.nameField.text, !name.isEmpty
    else { print("Name, Email or password is empty")
         return }
    
    registerNewUser(name: name, email: email, password: password) { [weak self] result in
        guard let self = self else { return }
        
        DispatchQueue.main.async {
            switch result {
            case .success(let authResult):
                print("User registered successfully: \(authResult.user.uid)")
                
                // Save user profile
                let newUser = User(uid: authResult.user.uid, name: name)
                PersistenceManager.saveUserProfile(user: newUser) { error in
                    if let error = error {
                        print("Error saving user profile: \(error.localizedDescription)")
                        // Handle the error (e.g., show an alert to the user)
                    } else {
                        print("User profile saved successfully.")
                        // Navigate to the next screen or show a success message

The problem is after I save these properties inside SignUpPresenter, the user is redirected to the main profileVC and there they chooses a photo as a profile photo and I use this code below to save it to user struct. But then it overwrite previous name property and I get it empty now. So my question is how can I get the previous saved properties and just add the profileImage to the struct there?

func updateUserProfileImageInFirestore(_ imageUrl: String) {
    guard let uid = Auth.auth().currentUser?.uid else {
        print("No user is currently signed in")
        return
    }
    
    let db = Firestore.firestore()
    db.collection("users").document(uid).updateData(["profileImageUrl": imageUrl]) { [weak self] error in
        if let error = error {
            print("Error updating user data: \(error.localizedDescription)")
            return
        }
        
        print("Profile image url successfully updated in Firestore")
        //self?.profileVC?.user?.profileImageUrl = imageUrl
        let profilePhoto = User(uid: "", name: "", profileImageUrl: imageUrl, bookmarkedRecipes: [])
        PersistenceManager.saveUserProfile(user: profilePhoto) {
            error in
            if let error = error {
                print("Error saving user profile: \(error.localizedDescription)")
            }
        }
0

There are 0 answers