从firebase检索数据失败

问题描述 投票:0回答:1

出于某种原因,在我从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]

swift xcode firebase firebase-realtime-database
1个回答
0
投票

由于异步操作,第三个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 
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.