I want to return Boolean after firebase code is executed(我想在执行 firebase 代码后返回布尔值)
本文介绍了我想在执行 firebase 代码后返回布尔值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在从 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 代码后返回布尔值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:我想在执行 firebase 代码后返回布尔值


猜你喜欢
- 类似于 Mail.app 的 iPad 模态视图控制器? 2022-01-01
- 在 Iphone SDK 的导航栏上添加多个按钮 2022-01-01
- Xcode 7.3 中带有 UILabel 的 UIStackView 2022-01-01
- 使用自动布局向 UIScrollView 添加动态大小的视图 2022-01-01
- GPS状态的广播接收器? 2022-01-01
- UITextView 内容插图 2022-01-01
- URL编码Swift iOS 2022-01-01
- 如何在 iPhone 模拟器中重置 NSUserDefaults 数据? 2022-01-01
- 网上有没有好的 UIScrollView 教程? 2022-01-01
- SetOnItemSelectedListener上的微调程序错误 2022-01-01