首页 > 解决方案 > 如何在 Swift 中保存实时 Firebase 数据库中的数据?

问题描述

因此,在我的代码中,您可以看到我想返回从 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
}

这是代码的图片,如果您想看的话

标签: iosswiftfirebase

解决方案


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

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

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
}

推荐阅读