简体   繁体   中英

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)
    }

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM