Reputation: 300
My code give me an infinite loop he never go in if or else, I'm pretty sure that because firebase get only asynchronous function.
I want to check if "random_hexa" exist, and get new random until I get a value who don't exist on my database
while (bool_check_while_exist == false)
{
ref.child("Salons").child(random_hexa).observeSingleEventOfType(.Value, withBlock: { (snapshot) in
if (snapshot.exists())
{
random_hexa = self.randomAlphaNumericString(5)
}
else
{
bool_check_while_exist = true
}
})
Upvotes: 0
Views: 179
Reputation: 598728
You're running a local while-loop that doesn't handle the asynchronous nature of your Firebase database (and of most of the modern internet). The correct flow would be to:
This can be most easily done with a recursive function:
func findUniqueNumber(ref: FIRDatabaseReference, withBlock: (value: Int) -> ()) {
let random_number = Int(arc4random_uniform(6) + 1)
ref.child(String(random_number)).observeSingleEventOfType(.Value, withBlock: { (snapshot) in
if (snapshot.exists())
{
print("Rejected \(random_number)")
self.findUniqueNumber(ref, withBlock: withBlock)
}
else
{
withBlock(value: random_number)
}
})
}
Which you then call as:
findUniqueNumber(ref, withBlock: { value in
print(value)
})
Upvotes: 1