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

Swift 4中如何从Firebase 3获取除当前用户外的所有用户

解决Firebase获取除当前用户外所有用户的问题

嘿,我来帮你搞定这个需求!你现在的代码已经能从Firebase获取所有用户了,要过滤掉当前登录用户其实只需要加个简单的判断就行,而且还要注意处理当前用户可能为nil的情况,避免崩溃。

修改后的完整代码

func fetchUser() {
    // 先安全获取当前用户ID,避免nil导致的问题
    guard let currentUserId = Auth.auth().currentUser?.uid else {
        print("当前用户未登录")
        return
    }
    
    Database.database().reference().child("users").observe(.childAdded, with: { (snapshot) in
        print(snapshot)
        
        if let dictionary = snapshot.value as? [String: AnyObject] {
            // 关键:判断当前遍历到的用户ID不等于当前登录用户ID
            guard snapshot.key != currentUserId else {
                return // 如果是当前用户,直接跳过
            }
            
            let user = User()
            user.id = snapshot.key
            user.name = dictionary["name"] as? String
            user.email = dictionary["email"] as? String
            user.profileImageUrl = dictionary["profileImageUrl"] as? String
            
            self.users.append(user)
            
            DispatchQueue.main.async {
                self.tableView.reloadData()
            }
        }
    }, withCancel: nil)
}

关键修改点说明

  • 安全解包当前用户ID:用guard let确保当前用户已经登录,避免Auth.auth().currentUser?.uid为nil时后续代码出错。
  • 添加用户过滤条件:在解析用户数据之前,判断snapshot.key(Firebase中每个用户节点的key就是用户ID)是否不等于当前登录用户ID,是的话才继续创建User对象并加入数组。
  • 避免重复数据(可选):如果你的users数组是全局的,每次调用fetchUser()前可以先执行self.users.removeAll(),防止重复添加用户(不过childAdded监听会在初始加载时遍历所有现有用户,之后只触发新用户添加,所以看你的业务需求决定是否需要清空)。

这样修改后,你的表格里就只会显示除当前登录用户外的其他用户啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:04:18