Reputation: 4009
So I am trying to change the contents of a variable with a snapshot that is being taken from my firebase database.
I have defined the variable and am then trying to use the setValue
method to change the value of the locally stored variable to the value that is held on the database. However despite getting no errors, my function is not running as it should be - nothing is added to the database despite my variable apparently being '0'.
This is my code:
var myVar = 1 as AnyObject
currentUserHasVotedVar.observeSingleEventOfType(.Value, withBlock: { snapshot in
myVar = snapshot.value
print(myVar)
//should be set to '0' from db
}, withCancelBlock: { error in
print(error.description)
})
if myVar as! NSObject == 0 {
print("Hasn't voted yet")
pollRef.childByAppendingPath("leave").childByAutoId()
myVar = 1
print(myVar)
}
Upvotes: 0
Views: 321
Reputation: 2533
In this case "myVar" will always be 1, because the single event of type Value is asynchronous. so the order of execution is first:
var myVar = 1 as AnyObject
then..
if myVar as! NSObject == 0 {
print("Hasn't voted yet")
pollRef.childByAppendingPath("leave").childByAutoId()
myVar = 1
print(myVar)
}
(this code is never executed because myVar is always 1) and at last it executes the content of the callback...
{ snapshot in
myVar = snapshot.value
print(myVar)
}, withCancelBlock: { error in
print(error.description)
}
In order to access the value of the firebase path in the "currentUserHasVotedVar" reference, you have to put your validation code inside the callback.
Upvotes: 1