SwiftER
SwiftER

Reputation: 1255

Firebase and Completion handler

Im currently using firebase to retrieve user info. once I receive the data I want to use the data outside of all closure the I create a completion block the problem is that I can not add the completion variable to the result because the result is inside another closure. How can fix this problem. Thank you in advance for the help.

 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

        })




    }

Upvotes: 1

Views: 1353

Answers (2)

Dravidian
Dravidian

Reputation: 9945

As far as i could understand your problem ::---

You want to send the emailID of your user in the completionBlock: once retrieved, But i still don't have any idea to what fireBaseAPI() is :-

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)
    })
}

Upvotes: 3

alexisSchreier
alexisSchreier

Reputation: 677

You could create a variable in your class (outside of the closure) and then store the snapshot.value result in that variable like this:

EDIT

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
    })
}

Upvotes: 1

Related Questions