Firebase Swift 3完成处理程序Bool [英] Firebase Swift 3 Completion handler Bool
问题描述
我正在尝试为函数编写一个完成处理程序,用于检查用户是否属于firebase中的团队成员。
我有一个公共类 customFunctions
,其中我创建了一个函数 ifUserIsMember
。我似乎有点卡在完成处理程序的想法,似乎无法弄清楚如何检查完成时的布尔值(如果这是有道理的)。这是我的代码类:
pre $ import $基础
导入GeoFire
导入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 team of a team)
completionHandler(false)
}
})
$ b $ p
$ b $ p $这里是我调用它的地方: / b>
@IBAction func signInButtonAction(_ sender:AnyObject){
//检查用户是否是团队成员
让userid = self.uid
checkFunctions.ifUserIsMember(userid:userid){success in
print(user is a me )
self.updateLocation(type:in)
}
}
无论 snapshot.hasChild(uerid)
实际上是否具有 userid $
解决方案>
func ifUserIsMember(userid:String,completionHandler:@escaping((_ exists:Bool) - > Void)){
let ref = FIRDatabase.database()。reference()
$ b ref.child(teammembers / \(userid))。observeSingleEvent(.value,与:{(快照)在
如果snapshot.exists(){
completionHandler(真)
}其他{
打印(用户不是一个团队的成员)
completionHandler(false)
}
})
}
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 function 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
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)
}
})
}
这篇关于Firebase Swift 3完成处理程序Bool的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!