从Firebase观察器代码块swift中的函数返回数据

我是firebase的新手,我想知道是否有任何可能的方法在观察者块中返回数据。 我有类ApiManager:NSObject ,在这个类中我想创建所有我的firebase函数,它将从数据库返回某种数据。 这是我在这堂课中的一个function

  func downloadDailyQuote() -> [String:String] { let reference = Database.database().reference().child("daily") reference.observeSingleEvent(of: .value) { (snap) in return snap.value as! [String:String] //I want to return this } return ["":""] //I don't want to return this } 

如果我现在做的事情就像let value = ApiManager().downloadDailyQuote()value包含空字典。 对此有什么解决方案吗?

更新:当您调用.observeSingleEvent时,您将异步调用该方法。 这意味着该方法将开始工作,但响应将在稍后进行,并且不会阻止主线程。 您调用此方法,但还没有数据,因此您返回一个空字典。

如果使用完成块,则只要方法操作完成,您就会获得数据。

 func downloadDailyQuote(completion: @escaping ([String:String]) -> Void) { let reference = Database.database().reference().child("daily") reference.observeSingleEvent(of: .value) { (snap) in if let dictionaryWithData = snap.value as? [String:String] { completion(dictionaryWithData) } else { completion(["" : ""]) } } } 
Interesting Posts