从Firebase数据库检索数据时执行顺序

时间:2018-01-21 13:18:03

标签: ios swift firebase-realtime-database

我想从Firebase检索数据并在函数中生成User()个对象。我做了以下课程:

class DatabaseQueries {
    // Database reference
    var ref: DatabaseReference?

    func findUserInfo() -> User {
        // Haal de userID op waaronder info is opgeslagen in de database.
        let userID = Auth.auth().currentUser?.uid

        // ref naar de database.
        ref = Database.database().reference()
        var user = User(email: "", group: "")

        ref?.child("Users").child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in
            // Get user value
            let value = snapshot.value as? NSDictionary
            let group = value?["group"] as? String ?? ""
            let email = value?["mail"] as? String ?? ""
            print(group)
            print(email)

            user.email = email
            user.group = group

        }) { (error) in
            print(error.localizedDescription)
        }
        print("Execute return")
        return user
    }
}

只返回数据,终止输出的顺序如下:

Execute return
User(email: Optional(""), group: Optional(""))
TestGroup
test.mail@gmail.com

如何首先获取用户结构,然后获取返回的值?

1 个答案:

答案 0 :(得分:3)

尝试使用具有调用任何Web服务/ firebase的功能的完成块.....等

  func findUserInfo(completion: @escaping (_ user: User) -> Void) {

    // Haal de userID op waaronder info is opgeslagen in de database.
    let userID = Auth.auth().currentUser?.uid

    // ref naar de database.
    ref = Database.database().reference()


    ref?.child("Users").child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in
        // Get user value
        let value = snapshot.value as? NSDictionary
        let group = value?["group"] as? String ?? ""
        let email = value?["mail"] as? String ?? ""
        print(group)
        print(email)
        var user = User(email: email, group: group)
        completion(user)

    }) { (error) in
        print(error.localizedDescription)

       var user = User(email: "", group: "")
        completion(user)
    }

}