bmmcc4
bmmcc4

Reputation: 65

Firebase, Cloud Firestore - SwiftUI display collection data in view

I have an app the uses Firebase for email/password authentication. When a user registers they register with an email, password, first name, and last name. This then creates a new document in my Cloud Firestore with the user's uid as the documentID. I have this successfully working, however, what is not working is displaying the user's data in a view.

I've written this fetchProfile function to retrieve the user's data from the Firestore. It prints the current users uid to the console.

import Foundation
import Firebase
import FirebaseFirestoreSwift
import FirebaseFirestore

struct UserProfile: Codable {
    var uid: String
    var firstName: String
    var lastName: String
}

class UserViewModel: ObservableObject {
    @Published var user: UserProfile = UserProfile(uid: "", firstName: "", lastName: "")
    private var db = Firestore.firestore()
    
    func createProfile(profile: UserProfile, completion: @escaping (_ profile: UserProfile?, _ error: Error?) -> Void) {
        do {
          let _ = try db.collection("users").document(profile.uid).setData(from: profile)
          completion(profile, nil)
        }
        catch let error {
          print("Error writing city to Firestore: \(error)")
          completion(nil, error)
        }
      }

      func fetchProfile(userId: String, completion: @escaping (_ profile: UserProfile?, _ error: Error?) -> Void) {
        let userId = Auth.auth().currentUser?.uid ?? ""
        db.collection("users").document(userId).addSnapshotListener { documentSnapshot, error in
            guard let document = documentSnapshot else {
                print("Error fetching document: \(error!)")
                return
            }
            guard document.data() != nil else {
                print("Document data was empty")
                return
            }
            self.user = UserProfile(uid: document.get("uid") as? String ?? "", firstName: document.get("firstName") as? String ?? "", lastName: document.get("lastName") as? String ?? "")
            let user = try? documentSnapshot?.data(as: UserProfile.self)
            print(user?.uid ?? "")
        }
    }  
}

When I try to display the text in my view it comes up blank. Here is my code for the view.

import SwiftUI
import Firebase
import FirebaseDatabase

struct UserProfileView: View {
   
    @EnvironmentObject var userProfile: UserViewModel

  var body: some View {
        VStack {
            Form {
                Text(userProfile.user.uid)
            }
            .navigationBarTitle("User \(userProfile.user.uid)")
        }
      } 
  }

Cloud Firestore Document

I am new to swift so any help is appreciated. Thank you

Upvotes: 1

Views: 326

Answers (2)

whenever you have a basic type that is not a string to display in a Text(), you can use this approach:

Text("\(userProfile.user.uid)")

Upvotes: 1

Afrik Docto
Afrik Docto

Reputation: 21

try

userProfile.user.uid.toString()

Upvotes: 0

Related Questions