首页 文章

如何从Firebase同步检索数据?

提问于
浏览
1

我有两个集合,即用户和问题 .

根据使用userId登录的用户,我从 users 集合中检索 currQuestion 值 .

根据 currQuestion 值,我需要从Firebase Questions 集合中检索 question 文档 .

我使用下面的代码来检索userId

rootRef.child("0").child("users")
        .queryOrderedByChild("userId")
        .queryEqualToValue("578ab1a0e9c2389b23a0e870")
        .observeSingleEventOfType(.Value, withBlock: { (snapshot) in

            for child in snapshot.children {
                self.currQuestion = child.value["currentQuestion"] as! Int
            }
            print("Current Question is \(self.currQuestion)")

            //print(snapshot.value as! Array<AnyObject>)
        }, withCancelBlock : { error in
                print(error.description)
        })

并检索问题

rootRef.child("0").child("questions")
.queryOrderedByChild("id")
.queryEqualToValue(currQuestion)
.observeSingleEventOfType(.Value, withBlock: { (snapshot) in
            for child in snapshot.children {
                print(child.value["question"] as! String)
            }

            }, withCancelBlock: { error in
                print(error.description)
        })

但是上面的代码是异步执行的 . 我需要解决方案使这个同步或如何实现监听器,以便我可以在 currQuestion 值更改后重新启动问题查询?

1 回答

  • 6

    编写自己的方法,将完成处理程序作为参数,并等待该代码块完成 . 像这样:

    func someMethod(completion: (Bool) -> ()){
     rootRef.child("0").child("users")
        .queryOrderedByChild("userId")
        .queryEqualToValue("578ab1a0e9c2389b23a0e870")
        .observeSingleEventOfType(.Value, withBlock: { (snapshot) in
    
            for child in snapshot.children {
                self.currQuestion = child.value["currentQuestion"] as! Int
            }
            print("Current Question is \(self.currQuestion)")
            completion(true)
            //print(snapshot.value as! Array<AnyObject>)
        }, withCancelBlock : { error in
                print(error.description)
        })
    }
    

    然后,只要你想调用该函数,就这样调用:

    someMethod{ success in
    if success{
    //Here currValue is updated. Do what you want.
    }
    else{
    //It is not updated and some error occurred. Do what you want.
    }
    }
    

    完成处理程序通常用于等待一段代码完全执行 . P.S. 只要它们不阻塞主线程,就可以通过添加完成处理程序(如上面显示的代码)来使异步请求同步 .

    它只是等待你的 currValue 先被更新(从服务器接收数据 async ),然后当你按照我的方式调用 someMethod 时,因为函数 someMethod 的最后一个也是唯一的参数是一个闭包(也就是说,尾随Closure),你可以跳过括号并调用它 . Here是关于闭包的很好的解读 . 由于闭包是类型(Bool) - >(),你只需告诉你 someMethod 什么时候完成任务就像 completion(true) 在我的代码中完成,然后在调用它时,用 success 调用它(你可以使用任何你想要的单词 WILL BE 类型为 Bool ,因为它被声明为这样,然后在函数调用中使用它 . 希望能帮助到你 . :)

相关问题