Swift Firebase Check if user exists

给你一囗甜甜゛ 提交于 2020-01-03 04:39:42

问题


What am i doing wrong? I have a database structure like the one shown in this image.
In appleDelegate.swift i just want to check if a certain user token actually exists under the "users" node. that is, if "users" has the child currentUserID (a string token). I understand observeSingleEvent is executed asynchronously.I get this error in swift: 'Application windows are expected to have a root view controller at the end of application launch'. in "func application(_ application: UIApplication" i have this code. I also have my completion handler function below.

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)
        }
    })
}

回答1:


I would suggest moving the code out of the app delegate and into an initial viewController. From there establish if this is an existing user and send the user to the appropriate UI.

.observeSingleEvent loads all of the nodes at a given location - one use would be to iterate over them to populate a datasource. If there were 10,000 users they would all be loaded in if you observe the /users node.

In this case it's really not necessary. It would be better to just observe the single node you are interested in and if it exists, send the user to a UI for existing users.

here's the code to do that

    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() )
        })
    }

snapshot.exists will be either true if the user node exists or false if not so the function presentUserViewController would accept a bool to then set up the UI depending on the user type.



来源:https://stackoverflow.com/questions/51273693/swift-firebase-check-if-user-exists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!