从firebase检索数据失败
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了从firebase检索数据失败相关的知识,希望对你有一定的参考价值。
出于某种原因,在我从firebase检索数据后,数据确实成功检索。
func retrieveData(user: User) {
//let userID = Auth.auth().currentUser?.uid
let email = user.emailAddress!
// print(email)
databaseRef?.child("userTable").child(email).observe(.value, with: { (snapshot) in
// Get user value
print("whats up ")
if let value = snapshot.value as? [String:String] {
let res = value["posts"]
user.deserialize(data: res!)
if( user === self.u1) {
print("they are same obj") // this will print, so they are pointing to the same address
}
print(self.u1.posts) // this also printed the things I want
}
// ...
})
if( user === self.u1) {
print("they are same obj outside") // this also prints
}
print(self.u1.posts) // but once they exist closure, this one just become empty, as as user.posts
}
我真的不明白这里发生了什么。看起来数据只是在关闭后正确存储。另外,我不知道为什么封闭外部的代码首先打印。非常感谢任何帮助!
这是运行结果
他们在[:]之外是相同的obj
怎么了他们是相同的obj [“@ @ hotmail 0”:RadiUs.Post]
答案
由于异步操作,第三个print语句中没有值(尚未)。
你的前两个print语句实际上是在你的第三个print语句之后执行的,即使它看起来不像。如果在每个print语句中创建断点,则可以查看执行顺序。
因此,为了保证数据从Firebase返回,您应该只调用此处的数据:
databaseRef?.child("userTable").child(email).observe(.value, with: { (snapshot) in
// Manipulate data here
}
如果您希望呼叫是同步的,则可以执行以下操作:
func retrieveData(user: User) {
//let userID = Auth.auth().currentUser?.uid
let email = user.emailAddress!
// print(email)
databaseRef?.child("userTable").child(email).observe(.value, with: { (snapshot) in
// Get user value
print("whats up ")
if let value = snapshot.value as? [String:String] {
let res = value["posts"]
user.deserialize(data: res!)
if( user === self.u1) {
print("they are same obj") // this will print, so they are pointing to the same address
}
print(self.u1.posts) // this also printed the things I want
}
// ...
})
if( user === self.u1) {
print("they are same obj outside") // this also prints
}
DispatchQueue.main.async{
print(self.u1.posts) // Now called sequentially
}
}
以上是关于从firebase检索数据失败的主要内容,如果未能解决你的问题,请参考以下文章
如何从 Firebase Task<AuthResult> 登录失败中检索错误代码?