0
votes

In my code, when the user signs up with email, pass and firstName, I get in firebase: their email related to an uid and, in Cloud Firestore, I get the firstName with uid as document id inside "Users" collection. I want to display user's name. How to do it?

EDIT:

In ModelData class, I have this code to signUp and added what was said below:

func signUp(){
      
      // checking....
      
      if email_SignUp == "" || password_SignUp == "" || reEnterPassword == "" || userName == ""{
          
          self.alertMsg = "Error"
          self.alert.toggle()
          return
      }
      
      if password_SignUp != reEnterPassword{
          
          self.alertMsg = "Error"
          self.alert.toggle()
          return
      }
      
      withAnimation{
          
          self.isLoading.toggle()
      }
      
    Auth.auth().createUser(withEmail: email_SignUp, password: password_SignUp) { [self]    (result, err) in
          
          withAnimation{
              
              self.isLoading.toggle()
          }
          
          if err != nil{
              self.alertMsg = "Error"
              self.alert.toggle()
              return
          }
         let db = Firestore.firestore()
        let docRef = db.collection("PROFILE").document(user?.uid ?? "")
        
        db.collection("PROFILE").document(result!.user.uid).setData(["userName" : self.userName])
      
        

        docRef.getDocument { (document, error) in
            if let document = document, document.exists {
                let data = document.data()
                return data.userName
            } else {
                // Handle error here
            }
        }
        
        
          result?.user.sendEmailVerification(completion: { (err) in
              
              if err != nil{
                  self.alertMsg = err!.localizedDescription
                  self.alert.toggle()
                  return
              }
              
              // Alerting User To Verify Email...
              
              self.alertMsg = ""
              self.alert.toggle()
          })
      }
  }

and in userName in getting the error Value of type '[String : Any]?' has no member 'userName'

1

1 Answers

1
votes

You would query your Users firestore collection for the document id (the uid), get() the data, then return the data.firstName:

let docRef = db.collection("Users").document(uid)

docRef.getDocument { (document, error) in
    if let document = document, document.exists {
        let data = document.data()
        return data.firstName
    } else {
        // Handle error here
    }
}

SOURCE