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

时间:2016-06-27 17:43:13

标签: ios swift return

我正在从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的值。

1 个答案:

答案 0 :(得分:2)

经典:

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

你需要一个完成块,只需

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)
}