【问题标题】:retrieve data from firebase failed从 firebase 检索数据失败
【发布时间】:2019-04-21 17:36:38
【问题描述】:

由于某种原因,我从 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 ["a@hotmail 0": RadiUs.Post]

【问题讨论】:

    标签: swift xcode firebase firebase-realtime-database


    【解决方案1】:

    由于异步操作,您的第三条打印语句(还)没有任何价值。

    您的前两个打印语句实际上在您的第三个打印语句之后执行,即使它看起来不像。如果您在每个打印语句处创建断点,您将能够看到执行顺序。

    所以为了保证数据是从 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 
        }
    }
    

    【讨论】:

    • 感谢 sfung3,我为每个打印语句添加了断点,但它们只是跳过了闭包内的断点。我不知道为什么。同时,有没有办法让这个按顺序执行?
    • 但是,如果我运行它(不添加断点),它会打印出闭包内的东西
    • 我更新了原始答案。如果您有任何其他问题,请告诉我。
    • 我更新了。但它仍然是同一个问题......还有其他帮助吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多