简体   繁体   English

从Firebase Observer代码块中的函数返回数据

[英]Returning data from function in Firebase observer code block swift

I'm new to firebase and I want to know if is any possible way to return data in observer block. 我是Firebase的新手,我想知道是否有任何可能的方法可以在观察者块中返回数据。 I have class ApiManager:NSObject and in this class I want to create all my firebase function that will return some kind of data from database. 我有ApiManager:NSObject类,在这个类中,我想创建我的所有firebase函数,该函数将从数据库返回某种数据。 This is one of my function in this class 这是我这堂课的功能之一

    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
} 

And if I now do something like let value = ApiManager().downloadDailyQuote() , value contains empty dictionary. 如果我现在执行let value = ApiManager().downloadDailyQuote() ,则value包含空字典。 Is any solution for that? 有什么解决办法吗?

Update: When you call .observeSingleEvent, you call the method asynchronously. 更新:调用.observeSingleEvent时,将异步调用该方法。 This means that the method will start working, but the response will come later and will not block the main thread. 这意味着该方法将开始工作,但是响应将稍后出现,并且不会阻塞主线程。 You invoke this method, but there is no data yet and therefore you return an empty dictionary. 您调用此方法,但尚无数据,因此返回空字典。

If you use the completion block, then you will get the data as soon as the method action is completed. 如果使用完成块,则方法操作完成后将立即获取数据。

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(["" : ""])
      }        
    }
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM