如何在iOS应用中通过Firebase获取登录用户的姓名数据?
问题解决:iOS应用无法从Firebase读取用户firstname字段
我开发了一个带登录系统的iOS应用,用户注册时会将数据存入Firebase Authentication和Firestore Database。进入首页后,页面需要显示数据库中用户的firstname字段,但目前只能正常获取用户UID,控制台输出如下:
UserID: Snapshot Value: Optional() No userData found
数据库结构为users集合下以用户UID为文档ID的文档,包含firstname等字段。
以下是我原代码:
import UIKit import FirebaseAuth import Firebase import FirebaseFirestore class HomeViewController: UIViewController { @IBOutlet weak var welcomeLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() fetchUserData() } func fetchUserData() { if let currentUser = Auth.auth().currentUser { let userId = currentUser.uid print("UserID:", userId) // Debugging let userRef = Database.database().reference().child("users").child(userId) userRef.observeSingleEvent(of: .value) { snapshot in print("Snapshot Value:", snapshot.value) // Debugging if let userData = snapshot.value as? [String: Any] { if let firstName = userData["firstname"] as? String { print("FirstName:", firstName) // Debugging // Update the welcomeLabel with the user's first name self.welcomeLabel.text = "Hello, \(firstName)" } else { print("Firstname not found in userData") } } else { print("No userData found") } } } } }
我的数据库规则:
rules_version = '2'; service cloud.firestore { match /databases/{database}/documents { match /{document=**} { allow read, write: if request.auth.uid != null; allow read, update, delete: if request.auth.uid == uid; } } }
问题根源&解决步骤
1. 核心问题:混用Firebase两种数据库服务
你把数据存在Firestore,但代码里调用的是Realtime Database的API(Database.database().reference()),二者是完全独立的数据库服务,自然读不到数据。
2. 修正数据读取代码(改用Firestore API)
替换原fetchUserData函数,使用Firestore的查询逻辑:
import UIKit import FirebaseAuth import FirebaseFirestore class HomeViewController: UIViewController { @IBOutlet weak var welcomeLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() fetchUserData() } func fetchUserData() { guard let currentUser = Auth.auth().currentUser else { return } let userId = currentUser.uid print("UserID:", userId) // 改用Firestore引用 let db = Firestore.firestore() let userRef = db.collection("users").document(userId) userRef.getDocument { snapshot, error in if let error = error { print("读取数据出错:\(error.localizedDescription)") return } guard let snapshot = snapshot, snapshot.exists else { print("用户文档不存在") return } print("Snapshot Value:", snapshot.data() ?? [:]) if let userData = snapshot.data() { if let firstName = userData["firstname"] as? String { print("FirstName:", firstName) // UI更新必须在主线程执行 DispatchQueue.main.async { self.welcomeLabel.text = "Hello, \(firstName)" } } else { print("userData中没有firstname字段") } } else { print("未获取到用户数据") } } } }
3. 修正Firestore规则(原规则逻辑冲突)
原规则中第一条已允许所有登录用户读写任意文档,第二条规则不会生效。建议改成更严谨的权限控制,确保用户只能访问自己的文档:
rules_version = '2'; service cloud.firestore { match /databases/{database}/documents { match /users/{userId} { allow read, write, update, delete: if request.auth.uid == userId; } } }
额外检查项
- 确认注册时数据确实写入Firestore的
users集合,且文档ID为用户UID - 确保项目已正确配置Firestore服务(而非仅配置Realtime Database)
内容的提问来源于stack exchange,提问作者SwiftCoder
相关产品推荐
相关产品推荐

