Swift Firebase 检查用户是否存在

caa*_*042 2 firebase completionhandler swift firebase-realtime-database

我究竟做错了什么?我有一个像这张图片中显示的那样的数据库结构。 我的数据结构
在 appleDelegate.swift 中,我只想检查“用户”节点下是否确实存在某个用户令牌。也就是说,如果“用户”具有子 currentUserID(字符串标记)。我了解observeSingleEvent 是异步执行的。我在swift 中收到此错误:“应用程序窗口应在应用程序启动结束时有一个根视图控制器”。在“func application(_ application:UIApplication”)中,我有这个代码。我在下面还有我的完成处理程序函数。

if let user = Auth.auth().currentUser{
        let currentUserID = user.uid
        ifUserIsMember(userId:currentUserID){(exist)->() in
            if exist == true{
                print("user is member")
                self.window?.rootViewController = CustomTabBarController()
            } else {
                self.window?.rootViewController = UINavigationController(rootViewController: LoginController())
            }
        }

        return true
    } else {
        self.window?.rootViewController = UINavigationController(rootViewController: LoginController())
        return true
    }
}

func ifUserIsMember(userId:String,completionHandler:@escaping((_ exists : Bool)->Void)){
    print("ifUserIsMember")
    let ref = Database.database().reference()
    ref.child("users").observeSingleEvent(of: .value, with: { (snapshot) in
        if snapshot.hasChild(userId) {
            print("user exists")
            completionHandler(true)
        } else {
            print("user doesn't exist")
            completionHandler(false)
        }
    })
}
Run Code Online (Sandbox Code Playgroud)

Jay*_*Jay 5

我建议将代码从应用程序委托中移到初始 viewController 中。从那里确定这是否是现有用户并将用户发送到适当的 UI。

.observeSingleEvent 加载给定位置的所有节点 - 一种用途是遍历它们以填充数据源。如果有 10,000 个用户,如果您观察 /users 节点,它们将全部加载。

在这种情况下,真的没有必要。最好只观察您感兴趣的单个节点,如果存在,将用户发送到现有用户的 UI。

这是执行此操作的代码

    if let user = Auth.auth().currentUser {
        let ref = self.ref.child("users").child(user.uid)
        ref.observeSingleEvent(of: .value, with: { snapshot in
            self.presentUserViewController(existing: snapshot.exists() )
        })
    }
Run Code Online (Sandbox Code Playgroud)

如果用户节点存在,snapshot.exists 将为真,否则为假,则函数 presentUserViewController 将接受一个布尔值,然后根据用户类型设置 UI。