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)
}
})
}
我建议将代码从应用程序委托中移出并移入初始视图控制器中。从那里确定这是否是现有用户并将用户发送到适当的 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() )
})
}
如果用户节点存在,snapshot.exists 将为 true;如果不存在,则为 false,因此函数presentUserViewController 将接受一个 bool 值,然后根据用户类型设置 UI。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)