Theetje
Theetje

Reputation: 29

Order of execution off while retrieving data from Firebase Database

I would like to retrieve data from Firebase and make User() objects within a function. I made the following class:

class DatabaseQueries {
    // Database reference
    var ref: DatabaseReference?

    func findUserInfo() -> User {
        // Haal de userID op waaronder info is opgeslagen in de database.
        let userID = Auth.auth().currentUser?.uid

        // ref naar de database.
        ref = Database.database().reference()
        var user = User(email: "", group: "")

        ref?.child("Users").child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in
            // Get user value
            let value = snapshot.value as? NSDictionary
            let group = value?["group"] as? String ?? ""
            let email = value?["mail"] as? String ?? ""
            print(group)
            print(email)

            user.email = email
            user.group = group

        }) { (error) in
            print(error.localizedDescription)
        }
        print("Execute return")
        return user
    }
}

The data is returned only the order is off the terminal output is as follows:

Execute return
User(email: Optional(""), group: Optional(""))
TestGroup
[email protected]

How do I first get the User struct to be filled and then get the value returned?

Upvotes: 0

Views: 53

Answers (1)

Shehata Gamal
Shehata Gamal

Reputation: 100549

Try using completion blocks with functions that call any web service / firebase .....etc

  func findUserInfo(completion: @escaping (_ user: User) -> Void) {

    // Haal de userID op waaronder info is opgeslagen in de database.
    let userID = Auth.auth().currentUser?.uid

    // ref naar de database.
    ref = Database.database().reference()


    ref?.child("Users").child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in
        // Get user value
        let value = snapshot.value as? NSDictionary
        let group = value?["group"] as? String ?? ""
        let email = value?["mail"] as? String ?? ""
        print(group)
        print(email)
        var user = User(email: email, group: group)
        completion(user)

    }) { (error) in
        print(error.localizedDescription)

       var user = User(email: "", group: "")
        completion(user)
    }

}

Upvotes: 3

Related Questions