Access Data Outside of Closure, Firebase ObserveSingleEvent // SWIFT

女生的网名这么多〃 提交于 2020-01-07 02:51:35

问题


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.


回答1:


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)
})


来源:https://stackoverflow.com/questions/40904141/access-data-outside-of-closure-firebase-observesingleevent-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!