Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
284 views
in Technique[技术] by (71.8m points)

ios - I want to return Boolean after firebase code is executed

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
}

Now, the return statement is returning before the firebase code is executed and change the value of yesOrNo.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...