Firebase Swift 3完成处理程序Bool
我试图编写一个函数的完成处理程序,检查用户是否是firebase中的一个团队的成员。
我有一个公共类customFunctions
,其中我创build了一个函数ifUserIsMember
。 我似乎有点卡在完成处理程序的想法,似乎无法弄清楚如何检查完成时的布尔值(如果这是有道理的)。 这是我的代码:
import Foundation import GeoFire import FirebaseDatabase public class customFunctions { func ifUserIsMember(userid: String, completionHandler: @escaping (Bool) -> ()) { let ref = FIRDatabase.database().reference() ref.child("teammembers").observeSingleEvent(of: .value, with: { (snapshot) in if snapshot.hasChild(userid){ completionHandler(true) }else{ print("user is not a member of a team") completionHandler(false) } }) } }
这就是我所说的:
@IBAction func signInButtonAction(_ sender: AnyObject) { //check if user is a member of a team let userid = self.uid checkFunctions.ifUserIsMember(userid: userid) { success in print("user is a member of a team") self.updateLocation(type: "in") } }
无论snapshot.hasChild(uerid)
实际上是否具有该userid
它似乎都会返回true
尝试使用: –
func ifUserIsMember(userid: String, completionHandler: @escaping ((_ exist : Bool) -> Void)) { let ref = FIRDatabase.database().reference() ref.child("teammembers/\(userid)").observeSingleEvent(of: .value, with: { (snapshot) in if snapshot.exists(){ completionHandler(true) }else{ print("user is not a member of a team") completionHandler(false) } }) }
对于遇到这个问题的其他人来说,这是为我解决的。
@IBAction func signInButtonAction(_ sender: AnyObject) { //check if user is a member of a team let userid = self.uid checkFunctions.ifUserIsMember(userid: userid) { (exist) -> () in if exist == true { print("user is a member of a team") self.updateLocation(type: "in") } else { print("user is not a member") } } } public class customFunctions { let ref = FIRDatabase.database().reference() func ifUserIsMember(userid: String, completionHandler: @escaping ((_ exist : Bool) -> Void)) { ref.child("teammembers").observeSingleEvent(of: .value, with: { (snapshot) in if snapshot.hasChild(userid){ completionHandler(true) }else{ print("user is not a member of a team") completionHandler(false) } }) }
}
Swift 3和Firebase 3.17.0
这将做的伎俩,检查NSNull
func ifUserIsMember(userid: String, completionHandler: @escaping (Bool) -> ()) { let ref = FIRDatabase.database().reference() ref.child("teammembers").observeSingleEvent(of: .value, with: { (snapshot) in guard snapshot.value is NSNull else { print("\(snapshot) exists") completionHandler(true) } print("\(snapshot) is not exists") completionHandler(false) }) }