简体   繁体   English

如何将实时 Firebase 数据库中的数据保存到 Swift 中?

[英]How to save data from Real Time Firebase Database in Swift?

So, in my code, you can see that I want to return the information that I retrieve from Firebase, but always the method returns an empty array, I'm new to Swift, can you please explain why this is happening and how can I make it work?所以,在我的代码中,你可以看到我想返回从 Firebase 检索到的信息,但该方法总是返回一个空数组,我是 Swift 的新手,你能解释一下为什么会发生这种情况,我该怎么做让它起作用? Thanks a lot.非常感谢。

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这是代码的图片,如果您想看的话

The database request work asynchronously, you have to add a completion handler.数据库请求异步工作,您必须添加一个完成处理程序。

And don't use NS... collection types in Swift并且不要在 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)
        
    })
    
}

And use it并使用它

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

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

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