Firebase和完成处理程序

时间:2016-09-03 20:15:13

标签: swift firebase

我目前正在使用firebase来检索用户信息。一旦我收到数据,我想在所有闭包之外使用数据,我创建一个完成块,问题是我无法将结果变量添加到结果中,因为结果在另一个闭包内。如何解决这个问题。提前感谢您的帮助。

 func userInfo(userId:String,completion:(result:String)->Void){


        fireBaseAPI().childRef("version_one/frontEnd/users/\(fireBaseAPI().currentUserId()!)/email").observeEventType(.Value, withBlock: {snapshot in

            let email = snapshot.value as! String

            //this is incorrect because it is inside a firebase closure how can I make it work I know i have it outside the closure but i will not be able to retrieve the info from firebase
            result = email

        })




    }

2 个答案:

答案 0 :(得分:3)

据我了解你的问题:: ---

您想要在检索到 completionBlock:时发送用户的emailID,但我仍然不知道fireBaseAPI()是什么: -

func userInfo(userId:String,completion:((result:String)->Void){
fireBaseAPI().childRef("version_one/frontEnd/users/\(fireBaseAPI().currentUserId()!)/email").observeEventType(.Value, withBlock: {snapshot in

        let email = snapshot.value as! String
        completion(result:email)
    })
}

答案 1 :(得分:1)

您可以在类中创建一个变量(在闭包之外),然后将snapshot.value结果存储在该变量中,如下所示:

修改

var emailResult: String?

func getUserEmail {
    fireBaseAPI().child("version_one/frontEnd/users/\(fireBaseAPI().currentUserId()!)/email").observeEventType(.Value, withBlock: {snapshot in
        let email = snapshot.value as! String
        self.emailResult = email
    })
}