You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

iOS端新Firebase登录后用户信息消失问题求助(Swift新手)

排查 & 解决 Firebase 用户信息登录后消失的问题

Hey there! Let's break down why your user data is vanishing after login—this is a super common pitfall when starting out with Swift and Firebase, so we'll get this sorted out step by step.

1. 先检查 Firebase 数据库安全规则

This is the #1 culprit for this kind of issue! Default rules for Realtime Database or Firestore often restrict access, but misconfigured rules can lead to a situation where you can write data during signup (while the new user session is active) but can't read it after logging back in.

For example, a flawed Realtime Database rule might look like this:

{
  "rules": {
    ".read": "auth != null",
    ".write": "auth != null"
  }
}

This allows any authenticated user to read/write all data, but if your code writes to a path that doesn't tie to the user's UID, you might accidentally overwrite or lose track of data.

Fix this by targeting the users/{uid} path explicitly:

{
  "rules": {
    "users": {
      "$uid": {
        ".read": "auth != null && auth.uid == $uid",
        ".write": "auth != null && auth.uid == $uid"
      }
    }
  }
}

This ensures only the owner of the data can read or write their own user info.

2. Verify your signup data-writing logic

From the snippet you shared, your signup flow likely creates an Auth user first, then writes their info to the database. Here are two common mistakes here:

  • You're using the wrong identifier (like username) as the database path instead of the user's unique uid from Firebase Auth.
  • You're not waiting for the database write to complete before navigating away, leading to incomplete or failed writes.

Here's a corrected version of your signup logic:

@objc func handleSignUp() {
    guard let username = usernameField.text, !username.isEmpty else { return }
    guard let email = emailField.text, !email.isEmpty else { return }
    guard let pass = passwordField.text, !pass.isEmpty else { return }
    guard let image = profileImageView.image else { return }

    // Step 1: Create Firebase Auth user
    Auth.auth().createUser(withEmail: email, password: pass) { authResult, error in
        guard let user = authResult?.user, error == nil else {
            print("Signup failed: \(error?.localizedDescription ?? "Unknown error")")
            return
        }

        // Step 2: Write user data to database using their UID as the path
        let userData: [String: Any] = [
            "username": username,
            "email": email,
            "profileImageUrl": "" // Add your image upload logic here later
        ]

        let userRef = Database.database().reference().child("users").child(user.uid)
        userRef.setValue(userData) { error, _ in
            if let error = error {
                print("Failed to save user data: \(error.localizedDescription)")
            } else {
                // Only navigate after the write is confirmed
                print("Signup and data save successful!")
                // self.navigationController?.pushViewController(HomeVC(), animated: true)
            }
        }
    }
}

3. Check your login data-reading logic

After login, make sure you're fetching data from the exact same path you wrote to during signup. Also, always use the current authenticated user's UID to fetch their info:

// Add this to your home/main view controller's viewDidLoad
override func viewDidLoad() {
    super.viewDidLoad()

    // Listen for auth state changes to ensure we only fetch data when a user is logged in
    Auth.auth().addStateDidChangeListener { auth, user in
        guard let currentUser = user else {
            // No user logged in—navigate to login screen
            // self.navigationController?.pushViewController(LoginVC(), animated: true)
            return
        }

        // Fetch the user's data using their UID
        let userRef = Database.database().reference().child("users").child(currentUser.uid)
        userRef.observeSingleEvent(of: .value) { snapshot in
            if let userData = snapshot.value as? [String: Any] {
                // Update your UI with the user's info here
                print("Loaded user data: \(userData)")
            } else {
                print("No user data found for UID: \(currentUser.uid)")
            }
        }
    }
}

4. Double-check Firebase Console for existing data

Sometimes we assume data was written successfully, but it wasn't. Head to your Firebase Console, navigate to the Database tab, and check if the users node contains data under the correct UID:

  • If the data exists in the console but won't load after login, the issue is with your read logic or security rules.
  • If the data doesn't exist in the console at all, your signup write logic has an error (like a failed async callback or incorrect path).

内容的提问来源于stack exchange,提问作者user9606399

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:15:07