我想在执行 firebase 代码后返回布尔值

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 代码后返回布尔值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Why local notification is not firing for UNCalendarNotificationTrigger(为什么没有为UNCalendarNotificationTrigger触发本地通知)
iOS VoiceOver functionality changes with Bundle Identifier(IOS画外音功能随捆绑包标识符而变化)
tabbar middle tab out of tabbar corner(选项卡栏中间的选项卡角外)
Pushing UIViewController above UITabBar(将UIView控制器推送到UITabBar上方)
Dropbox Files.download does not start when number of files in folder is gt; 1000(当文件夹中的文件数为1000时,Dropbox Files.Download不会启动)
How can I sync two flatList scroll position in react native(如何在本机Reaction中同步两个平面列表滚动位置)