简体   繁体   中英

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? 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

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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