我想在执行 firebase 代码后返回布尔值 [英] I want to return Boolean after firebase code is executed

查看:12
本文介绍了我想在执行 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 代码后返回布尔值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆