Badr Filali
Badr Filali

Reputation: 300

How can I change my value with Firebase

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

Answers (1)

Frank van Puffelen
Frank van Puffelen

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:

  1. generate a random value
  2. start a call to the database to see if that value already exists
  3. wait for that call to complete
  4. if the value doesn't exist yet, be happy
  5. else start again

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

Related Questions