I want to return Boolean after firebase code is executed

前端 未结 1 567
臣服心动
臣服心动 2021-01-29 03:40

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          


        
相关标签:
1条回答
  • 2021-01-29 04:05

    The classic:

    You cannot return anything from a method which contains an asynchronous task

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

    Or easier

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

    And call it with

    checkBought("Foo") { flag in
       print(flag)
    }
    
    0 讨论(0)
提交回复
热议问题