Firebase Authentication iOS登录后如何获取Firestore用户详情
How to Fetch and Display User's First Name from Firestore After Login
Hey there! Let's get that user's first name showing up on your welcome screen smoothly. Here's a clear, step-by-step guide tailored to your setup:
Step 1: Get the Current Authenticated User's UID
First, retrieve the UID of the logged-in user—this is the key you used to store their data in Firestore. Use Firebase Auth's currentUser property:
import FirebaseAuth import FirebaseFirestore // In your welcome view controller (or wherever you need to display the name) guard let currentUser = Auth.auth().currentUser else { // Handle the case where no user is logged in (e.g., redirect to login screen) print("No user is currently authenticated") return } let userUID = currentUser.uid
Step 2: Fetch User Data from Firestore
Next, query Firestore using the UID to pull up the user's document. Make sure to match the collection name and field names you used when saving the data (adjust them if your setup differs):
let firestoreDB = Firestore.firestore() // Replace "users" with your actual collection name firestoreDB.collection("users").document(userUID).getDocument { (documentSnapshot, error) in if let error = error { print("Failed to fetch user data: \(error.localizedDescription)") return } guard let document = documentSnapshot, document.exists else { print("User document not found in Firestore") return } // Extract the first name (match the field name you saved, e.g., "First name" or "firstName") if let firstName = document.data()?["First name"] as? String { // Update the UI on the main thread (Firestore callbacks run in background) DispatchQueue.main.async { self.welcomeLabel.text = "Welcome, \(firstName)!" } } else { print("First name field missing or invalid in user document") } }
Critical Notes to Avoid Issues
- Firestore Security Rules: Ensure your rules allow authenticated users to read their own data. Update your Firestore rules to something like this:
rules_version = '2'; service cloud.firestore { match /databases/{database}/documents { match /users/{userId} { allow read, write: if request.auth != null && request.auth.uid == userId; } } } - Field Name Exact Match: Double-check that the field name in your code (
"First name") matches exactly what you stored in Firestore—capitalization and spacing matter! - Main Thread for UI: Always wrap UI updates in
DispatchQueue.main.asyncsince Firestore's completion handler runs on a background thread.
That should do it! Once you implement this, your welcome label will greet the user by their first name right after login.
内容的提问来源于stack exchange,提问作者iceman_caw
相关产品推荐
相关产品推荐

