Firebase无法获取当前用户ID及按UID查询数据问题求助
It looks like you're close to solving these issues—let's break down the fixes step by step:
1. Safely Retrieve the Current User ID
While you check if currentUser exists, using force unwrapping (!) to get the UID is risky (it can cause crashes if currentUser becomes nil unexpectedly after the check). Instead, use optional binding to safely access the UID:
if let currentUser = Auth.auth().currentUser { let userID = currentUser.uid print("Current user ID is \(userID)") // Rest of your data fetching code goes inside this block } else { print("No user is logged in—handle this case appropriately (e.g., redirect to login)") }
2. Fetch Only the Current User's Data
The reason you're getting all users' data is that you're observing the entire Details node. To fetch only the data belonging to the current user, you need to target the specific child node under Details that matches their UID.
Assuming your Firebase Realtime Database structure looks like this (where each user's data is stored under their UID):
Details - abc123 (userUID) - name: "John Doe" - email: "john@example.com" - xyz789 (another userUID) - name: "Jane Smith"
Modify your data observation code to point directly to the user's node:
// Inside the if let currentUser block self.databaseHandler = self.readData.child("Details").child(userID).observe(.value, with: { (snapshot) in // Safely unwrap the snapshot value instead of force unwrapping if let userData = snapshot.value as? [String: AnyObject] { self.postData = userData print("Fetched user data: \(self.postData)") // Don't forget to reload your UI here if you're displaying this data } else { print("No data found for this user") } })
If Your Data Structure Uses UID as a Field (Not a Child Key)
If your Details entries store the UID as a field inside each object (like {"uid": "abc123", "name": "John"}), use a query to filter results:
let query = self.readData.child("Details").queryEqual(toValue: userID, childKey: "uid") query.observe(.value) { snapshot in // Process the query results (note: this will return a snapshot with matching children) for child in snapshot.children { if let childSnapshot = child as? DataSnapshot, let userData = childSnapshot.value as? [String: AnyObject] { self.postData = userData break // Assuming you only want one matching entry } } }
Key Takeaways
- Always use optional binding to safely access
currentUserand its properties to avoid crashes. - Target the specific user's node (or use a query) instead of observing the entire
Detailscollection to get only the data you need.
内容的提问来源于stack exchange,提问作者user7853453

