Jake Ols Jake Ols - 1 month ago 40
Swift Question

Firebase Swift 3 Completion handler Bool

I'm trying to write a completion handler for a function that checks if a user is a member of a team in firebase.

I have a public class customFunctions in which I created a func ifUserIsMember. I seem to be a little stuck on the idea of completion handlers, and can't seem to figure out how to check the bool value on completion (if that makes sense). Here's my code for the 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)
}


})

}



}


And here is where I'm calling it:

@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")

}


}


It seems that it's returning true regardless of whether snapshot.hasChild(uerid) actually has that userid

Answer

Try using :-

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