我创建了上面的函数来检查Firebase数据库中是否存在用户:
func userExists(userUid: String) -> Bool {
var userExists: Bool = false
DBRef.child("users").child(userUid).observeSingleEventOfType(.Value, withBlock: { (snapshot: FIRDataSnapshot) in
if snapshot.exists(){
userExists = true
}else{
userExists = false
}
})
return userExists
}
问题是userExists函数总是返回" false",即使userExists变量在withBlock中设置为true也是如此。有什么帮助吗?谢谢!
答案 0 :(得分:1)
您不应在同一函数中使用return和closure块,因为该函数将在执行块之前返回该值。 你可以使用这样的东西:
func userExists(userUid: String, completion: (exists: Bool) -> Void) {
var userExists: Bool = false
DBRef.child("users").child(userUid).observeSingleEventOfType(.Value, withBlock: { (snapshot: FIRDataSnapshot) in
if snapshot.exists(){
completion(true)
}else{
completion(false)
}
})
}
然后,你只需致电:
if userExists(userId, completion: {
// Code here
})