Firebase Swift 3完成处理程序Bool

时间:2016-10-19 15:07:32

标签: ios swift firebase firebase-realtime-database completionhandler

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

我有一个公共课customFunctions,我在其中创建了一个函数ifUserIsMember。我似乎有点坚持完成处理程序的想法,似乎无法弄清楚如何在完成时检查bool值(如果这是有道理的)。这是我的课程代码:

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

3 个答案:

答案 0 :(得分:0)

尝试使用: -

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

答案 1 :(得分:0)

对于遇到此问题的其他人来说,这就是为我解决的问题。

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


    })

}

}

答案 2 :(得分:0)

Swift 3& Firebase 3.17.0

这将解决问题,检查NSNull

Label