从Firebase观察器代码块Swift中的函数返回数据 [英] Returning data from function in Firebase observer code block swift

查看:52
本文介绍了从Firebase观察器代码块Swift中的函数返回数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Firebase的新手,我想知道是否有任何可能的方法可以在观察者块中返回数据.我有一个类ApiManager:NSObject,在这个类中,我想创建所有的firebase函数,该函数将从数据库返回某种数据.这是我在此类课程中的功能之一

I'm new to firebase and I want to know if is any possible way to return data in observer block. 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. 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
} 

如果我现在做类似let value = ApiManager().downloadDailyQuote()的操作,则value包含空字典.有什么解决办法吗?

And if I now do something like let value = ApiManager().downloadDailyQuote(), value contains empty dictionary. Is any solution for that?

推荐答案

更新:调用.observeSingleEvent时,将异步调用该方法.这意味着该方法将开始工作,但是响应将稍后出现,并且不会阻塞主线程.您调用此方法,但尚无数据,因此返回空字典.

Update: When you call .observeSingleEvent, you call the method asynchronously. 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(["" : ""])
      }        
    }
 }

这篇关于从Firebase观察器代码块Swift中的函数返回数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆