我想在执行firebase代码后返回Boolean

我正在从Firebase Google检索数据。 我正在检查收到的数据是否过期。

func checkBought(movieName : String) -> Bool{ var yesOrNo = false boughtRef.observeEventType(.Value, withBlock: { (snap) in if snap.value![movieName]! != nil { if self.timestamp > snap.value![movieName]! as! Double { //expire print("expire") yesOrNo = false } else { //not expire print("not expire") yesOrNo = true } } else { //not bought yet print("No movie") yesOrNo = false } }) return yesOrNo } 

现在,return语句在执行firebase代码之前返回,并更改yesOrNo的值。

经典:

您不能从包含异步任务的方法返回任何内容

你需要一个完成块

 func checkBought(movieName : String, completion:(Bool) -> Void) { boughtRef.observeEventType(.Value, withBlock: { (snap) in if snap.value![movieName]! != nil { if self.timestamp > snap.value![movieName]! as! Double { //expire print("expire") completion(false) } else { //not expire print("not expire") completion(true) } } else { //not bought yet print("No movie") completion(false) } }) } 

或者更容易

 func checkBought(movieName : String, completion:(Bool) -> Void) { boughtRef.observeEventType(.Value, withBlock: { (snap) in if let movieStamp = snap.value![movieName] as? Double where self.timestamp <= movieStamp { //not expire print("not expire") completion(true) } else { // expire or not bought yet print("expire or no movie") completion(false) } }) } 

并称之为

 checkBought("Foo") { flag in print(flag) }