Manny
Manny

Reputation: 91

Access Data Outside of Closure, Firebase ObserveSingleEvent // SWIFT

When I first asked this question I hadn't really done my research. But after 20+ hours on this, I have structure exactly like in Firebase docs. But, I can't access any of the data outside of the closure. Here is the struct where the data should be written in to:

    struct UserStruct {
        let name : String!
        let age : String!
    }

And when it gets called, everything is written perfect in the database, inside the closure it doesn't print nil, it does print the actual value obviously. I have already tried

    DispatchQueue.main.async {

    }

But that didn't work either, somebody guide me! Any help is appreciated, this is my last issue with Firebase.

     let currentUser = FIRDatabase.database().reference(withPath: "users").child((FIRAuth.auth()!.currentUser?.uid)!)
        currentUser.observeSingleEvent(of: .value, with: { snapshot in
        let value = snapshot.value as? NSDictionary
        let name = value?["name"] as? String
        let age = value?["age"] as? String
        self.userAdded.insert(UserStruct(name: name, age: age), at: 0) // 1
        let user = UserStruct.init(name: name, age: age) // 2

        print("1 \(user.name)")
        print("2 \(self.userAdded[0].name!)")
    })

I wrote two ways of getting the data, number two(2) is the way Firebase suggests, but I can't even get a hold of user outside the closer like I can with the Struct.

Upvotes: 0

Views: 877

Answers (1)

alexisSchreier
alexisSchreier

Reputation: 677

Your user object that you create in the closure gets deallocated when the closure finishes what it has to do. As @Jay said in the comment, you need to store the data that you get in your closure in a variable outside of your closure. A quick and dirty way to test this out would be to create a variable in the class you're in and assign the user you create in your closure to that variable and print it out to see if it worked:

//add a property in your class to store the user you get from Firebase
var retrievedUser: UserStruct?

let currentUser = FIRDatabase.database().reference(withPath: "users").child((FIRAuth.auth()!.currentUser?.uid)!)
currentUser.observeSingleEvent(of: .value, with: { snapshot in
    let value = snapshot.value as? NSDictionary
    let name = value?["name"] as? String
    let age = value?["age"] as? String

    let user = UserStruct.init(name: name, age: age)

    //assign the user retrieved from Firebase to the property above
    self.retrievedUser = user
    //print the local copy of the retrived user to test that it worked
    print(retrievedUser)
})

Upvotes: 1

Related Questions