我正在从 Firebase Google 检索数据.我正在检查我收到的数据是否过期.
I'm retrieving data from Firebase Google. I'm checking the data i received is expire or not.
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 的值.
Now, the return statement is returning before the firebase code is executed and change the value of yesOrNo.
经典之作:
您不能从包含异步任务的方法返回任何内容
你需要一个完成块,很简单
You need a completion block, simply
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)
}
这篇关于我想在执行 firebase 代码后返回布尔值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!