如何让我的程序等待Firebase响应IOS

时间:2017-09-27 13:56:36

标签: ios firebase swift3 firebase-realtime-database

您好我查看了很多处理Firebase异步数据库的问题,但没有答案解决了我的问题:

Here is a screenshot of my firebase's structure

Here is a picture of the Output

我的for循环在进入if之前连续35次打印“返回错误”(snapshot.children的数量)。有没有办法强制程序等待firebase响应?提前谢谢。

        ref.child("Events").observe(.value, with: { (snapshot) in

            for child in snapshot.children{
                multiple = false
                print("REMISE A FALSE")

            if let result = snapshot.children.allObjects as? [DataSnapshot] {

                    for child in result {
                        var eventForClub = child.key as! String

                        self.ref.child("Events").child("\(eventForClub)").observe(.value, with: { (snapshot) in
                            for child in snapshot.children{

                                let snap = child as! DataSnapshot
                                let event = snap.value as? [String:Any]
                                let end_time_test = event?["end_time"] as? String
                                let name_time = event?["name"] as? String
                                print(end_time_test)

                                let dateFormatter = DateFormatter()
                                dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
                                dateFormatter.timeZone = TimeZone(abbreviation: "GMT+2:00")

                                let end = dateFormatter.date(from: end_time_test!)!

                                if(end.compare(self.currentDate!) == .orderedAscending || multiple == true)
                                {
                                    print("date erronée")

                                }

                else{
                print(multiple)
                print("GOOD")
                multiple = true}

1 个答案:

答案 0 :(得分:0)

如果我理解正确你有一个Firebase事件节点并且每个事件都有一个变量“currentDate”是某种日期格式?你想通过打印它们来显示它们吗?

ref.child("Events").observe(.value, with: { (snapshot) in
  if snapshot.value is NSNull{
     //handles errors
  }
  else{
     if let event= snapshot.value as? [String: String]{ //could be AnyObject if you have more then just strings
      if let eventClub = event["eventForClub"] as? [String: String]//Could also be a dictionary{
          let currentDate = eventClub["currentDate"]
          let endTime = eventClub["end_time"]
          //compare
          //print if true/false
      }    
     }
  }
})