【发布时间】:2017-07-07 15:09:04
【问题描述】:
在 else 语句中的 @IBaction func login 内部,我调用 startObserving()。为什么不在主线程上执行?
这条语句print("executed") 在self.startObservingDB(callback: { (snapValue) in 中的代码在else 语句中被求值之前被执行。
我不希望 startObservingDB 在从 Firebase 接收到 snapValue 之前返回。如何让 else 语句中的 startObservingDB 等待 Firebase 完成其任务然后继续执行?
@IBAction func logIn(_ sender: AnyObject) {
FIRAuth.auth()?.signIn(withEmail: email.text!, password: password.text!, completion: { (authData, error) in
if error != nil {
//
} else {
self.startObservingDB(callback: { (snapValue) in
if snapValue != nil {
print("should segue")
self.performSegue(withIdentifier: "LogInToTabBarController", sender: self)
}
})//end of startObservingDB
//prints before code in else statement, inside self.startObservingDB(callback: { (snapValue) is evaluated
print("executed")
}
})
}
func startObservingDB(callback:@escaping ((_ snapShot:FIRDataSnapshot?) -> Void)){
// check if user is singed in
guard let uid = FIRAuth.auth()?.currentUser?.uid else {
return
}
dbRef.child(uid).child("profile").observeSingleEvent(of: .value, with: { (snapshot: FIRDataSnapshot) in
//pass snapshot vale to callback closure so as to make the values available when calling startObservingDB
callback(snapshot.value as? FIRDataSnapshot)
}, withCancel: { (Error:Any) in
print("Error firebase \(Error)")
print("You are not a cleaner")
})
dbRef.removeAllObservers()
} // end of startObserving
【问题讨论】:
标签: ios swift3 grand-central-dispatch completionhandler