在闭包之外访问数据,Firebase ObserveSingleEvent // SWIFT
当我第一次问这个问题时,我还没有真正完成研究。但是经过20多个小时之后,我的结构与Firebase文档中的结构完全一样。但是,我无法在闭包之外访问任何数据。这是应该将数据写入其中的结构:
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!
}
当它被调用时,一切都完美地写入了数据库中闭包它不会打印nil,它确实会打印实际值。我已经尝试过
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 {
}
但是那也不行,有人来指导我!感谢您的帮助,这是我关于Firebase的最后一个问题。
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!)")
})
我写了两种获取数据的方法,二(2)是Firebase建议的方法,但是我什至无法像Struct那样在更近的地方拥有用户。
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.
您在闭合中创建的 user
对象在闭合完成后将被释放去做。就像@Jay在评论中所说的那样,您需要将在闭包中获得的数据存储在闭包的变量 outside 中。一种快速而肮脏的测试方法是在您所在的类中创建一个变量,然后将在闭包中创建的 user
分配给该变量并打印出来看看它是否有效:
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)
})