Firebase Swift 3 完成处理程序 Bool

Firebase Swift 3 Completion handler Bool

我正在尝试为检查用户是否是 firebase 团队成员的函数编写完成处理程序。

我有一个 public class customFunctions,我在其中创建了一个函数 ifUserIsMember。我似乎有点坚持完成处理程序的想法,并且似乎无法弄清楚如何在完成时检查 bool 值(如果这有意义的话)。这是我的 class:

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