如何在另一UIViewController中显示Firebase登录用户的用户名
我现在想在另一个UIViewController(HomeViewController)中显示Firebase数据库内的用户名,当前数据库里的用户名是示例值"test",希望不同用户登录后能在界面看到各自的用户名。
我的Firebase数据库结构是这样的:
exsample-bde49 users: profile: oAPjqYRrO1NADm1i1YH1qK7FOk53 photoURL: "https://firebasestorage.googleapis.com/v0/b/exs..." username: "test"
LoginViewController中的handleSignIn方法:
@objc func handleSignIn() { guard let email = emailField.text else { return } guard let pass = passwordField.text else { return } setContinueButton(enabled: false) continueButton.setTitle("", for: .normal) activityView.startAnimating() Auth.auth().signIn(withEmail: email, password: pass) { user, error in if error == nil && user != nil { self.dismiss(animated: false, completion: nil) } else { print("Error logging in: \(error!.localizedDescription)") self.restforms() } } }
HomeViewController的代码:
import Foundation import UIKit import Firebase class HomeViewController:UIViewController { @IBAction func nextViewButton(_ sender: Any) { print("test press") self.performSegue(withIdentifier:"seccondview", sender: self) } override func viewDidLoad() { super.viewDidLoad() } @IBAction func handleLogout(_ sender:Any) { try! Auth.auth().signOut() self.dismiss(animated: false, completion: nil) } @IBAction func logout(_ sender: Any) { try! Auth.auth().signOut() self.dismiss(animated: false, completion: nil) } }
别担心,这个实现起来很简单,咱们一步步来:
第一步:给HomeViewController添加显示用户名的UI元素
首先你需要在HomeViewController的Storyboard或者代码里添加一个UILabel,用来展示用户名。如果用代码声明的话,在类里加这个IBOutlet:
// 在HomeViewController类内部添加 @IBOutlet weak var usernameLabel: UILabel!
记得在Storyboard里把这个Label和IBOutlet关联好哦。
第二步:读取当前用户的数据库信息
用户登录成功后,Firebase Auth会自动保存当前用户的会话信息,我们可以通过Auth.auth().currentUser拿到当前用户,再用他的UID去数据库里匹配对应的用户名。
修改HomeViewController的viewDidLoad方法,加上读取数据库的逻辑:
override func viewDidLoad() { super.viewDidLoad() // 先检查是否有已登录的用户 guard let currentUser = Auth.auth().currentUser else { // 如果没有用户登录,直接跳回登录页 self.dismiss(animated: true, completion: nil) return } // 获取当前用户的唯一ID let userId = currentUser.uid // 定位到Firebase数据库中对应用户的profile节点 let userProfileRef = Database.database().reference() .child("users") .child("profile") .child(userId) // 一次性读取用户数据(如果需要实时更新可以用observe方法) userProfileRef.observeSingleEvent(of: .value) { snapshot in guard let userData = snapshot.value as? [String: Any] else { print("无法解析用户数据") return } // 取出用户名并设置到Label上 if let username = userData["username"] as? String { self.usernameLabel.text = username } } }
第三步:确保数据库权限配置正确
一定要检查Firebase数据库的安全规则,确保已登录用户能读取自己的profile数据。推荐设置这样的规则:
{ "rules": { "users": { "profile": { "$uid": { ".read": "$uid === auth.uid", ".write": "$uid === auth.uid" } } } } }
这个规则限定了只有用户本人才能读写自己的profile信息,既安全又符合你的需求。
小优化:调整登录后的跳转逻辑(可选)
你现在的handleSignIn方法是直接dismiss登录页,其实可以改成直接跳转HomeViewController,这样流程更清晰。比如把self.dismiss(animated: false, completion: nil)替换成:
// 假设你用导航控制器管理页面 let homeVC = self.storyboard?.instantiateViewController(withIdentifier: "HomeViewController") as! HomeViewController self.navigationController?.pushViewController(homeVC, animated: true)
当然如果你的现有模态跳转流程没问题,保持原样也可以,只要HomeViewController能正常读取数据就行。
内容的提问来源于stack exchange,提问作者user10238568

