【问题标题】:How to save data from Real Time Firebase Database in Swift?如何在 Swift 中保存实时 Firebase 数据库中的数据?
【发布时间】:2021-05-24 15:44:42
【问题描述】:

所以,在我的代码中,您可以看到我想返回从 Firebase 检索到的信息,但该方法总是返回一个空数组,我是 Swift 新手,您能解释一下为什么会这样吗?我怎样才能让它工作?非常感谢。

var catalog:[String:NSDictionary] = [String():NSDictionary()]
func readCatalogInfo()->[String:NSDictionary]{
    
    let ref = Database.database(url: "https://reforestar-database-default-rtdb.europe-west1.firebasedatabase.app/").reference()
    
    _ = ref.child("trees").observe(.value, with: {snapshot in
        
        guard let information:[String:NSDictionary] = snapshot.value as? [String:NSDictionary] else {
            print("Error in getting information about the Trees")
            return
        }
        self.catalog = information
        
    })
    
    return self.catalog
}

Here's a pic of the code if you want to see it

【问题讨论】:

  • 这能回答你的问题吗? Returning data from async call in Swift function
  • @vadian 提供了一个很好的答案,这可能是解决方案。请注意,有多种方法可以实现这一点,完成处理程序就是其中之一。如果您打算稍后使用数据,例如在目录中,那么将其填充到 Firebase 闭包中并且不尝试返回它也可以。例如;如果用户登录并在此后的某个时间点他们想要在其目录中查找零件。该目录可以在他们登录时预加载。我们不知道您的具体用例,因此请考虑如何使用该数据来确定解决方案。

标签: ios swift firebase


【解决方案1】:

数据库请求异步工作,你必须添加一个完成处理程序。

并且不要在 Swift 中使用 NS... 集合类型

var catalog = [String:[String:Any]]()

func readCatalogInfo(completion: @escaping ([String:[String:Any]]) -> Void) {
    
    let ref = Database.database(url: "https://reforestar-database-default-rtdb.europe-west1.firebasedatabase.app/").reference()
    
    _ = ref.child("trees").observe(.value, with: {snapshot in
        
        guard let information = snapshot.value as? [String:[String:Any]] else {
            print("Error in getting information about the Trees")
            return
        }
        completion(information)
        
    })
    
}

并使用它

readCatalogInfo() { [weak self] result in 
   self?.catalog = result
}

【讨论】:

  • 感谢您的回复,但它仍然无法正常工作,self.catalog 是一个变量,可通过所有视图控制器使用,当我存在该方法时,我得到一个空数组...跨度>
  • 我明白了,我只能使用 readCatalogInfo() 方法中的信息,但是有什么方法可以使用它之外的信息,将信息保存在全局变量或缓存中,正如我告诉你的,我是 Swift 的新手,所以这可能很有用。 @vadian ?? :)
  • 运行你需要在闭包内运行的代码。
猜你喜欢
  • 2021-10-09
  • 2021-05-24
  • 2020-04-22
  • 2021-10-07
  • 1970-01-01
  • 1970-01-01
  • 2021-12-30
  • 2020-10-10
  • 1970-01-01
相关资源
最近更新 更多