Alex
Alex

Reputation: 287

How to get the first name of the logged in User from firebase using Swiftui?

How to to get the first name of the current user which is logged in.

This is how my try looks like:

 var ref: DatabaseReference!

    ref = Database.database().reference()
    let db = Firestore.firestore()
   let userID = Auth.auth().currentUser?.uid
    print(userID)
    ref.child("users").child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in
      // Get user value
      let value = snapshot.value as? NSDictionary
      let username = value?["firstname"] as? String ?? ""
      print(username)

      // ...
      }) { (error) in
        print(error.localizedDescription)
    }

Upvotes: 0

Views: 1648

Answers (1)

Peter Haddad
Peter Haddad

Reputation: 80914

Try the following:

let userId = Auth.auth().currentUser?.uid else { return }
let docRef = db.collection("users").document(userId)
docRef.getDocument(source: .cache) { (document, error) in
  if let document = document {
    let name = document.get("firstname")
    print("Cached document data: \(name)")
  } else {
    print("Document does not exist in cache")
  }
}

You are using cloud firestore but in your code, you are using the Realtime database. You need to check the following docs related to cloud firestore:

https://firebase.google.com/docs/firestore/quickstart

Upvotes: 2

Related Questions