简体   繁体   中英

Firebase While Loop Swift 4

I was working on a new page in one of my apps and was facing a small issue involving Firebase and While Loops. Below is my code:

var user = User()

var i = 0

while i < 101 {

print("Print Statement 1: " + String(i))

//Correctly prints i, incrementing it by 1 every time like it should.

self.ref.child("Directory")
    .child(String(i))
    .observeSingleEvent(of: .value, with: { (snapshot) in

        print("Print Statement 2: " + String(i))

        //Always prints 101

        let nameValue = snapshot.value as? NSDictionary

        if nameValue != nil {

            user.id = String(i)

            //Always get set to 101, and not the current value of i

        }

    }) { (error) in

        print(error.localizedDescription)

}

i += 1

}

Logs:

Print Statement 1 :

0
1
2
3
4
etc.

Print Statement 2:

101
101
101
101
101
etc.

Pretty much the only question I have here is why is the second print statement always printing 101 and not the incremented value of i. Is this something related to the Firebase Observer not observing the single event every time the while loop is executed? Also, what can I do to fix this?

Thanks, KPS

That's because firebase queries your request asynchronously and the completion handler (where you're printing i ) so happens to get called when your while loop is finished and i has a value of 101.

Edit: A workaround would be to have a separate counter and incrementing only when you're checking for values. So, that would change only when the results are in and you can know which result was nil. However, this won't be reliable as network requests can be slow and unordered but should work in most cases

var user = User()

var i = 0

var counter = 0

while i < 101 {

...

self.ref.child("Directory")
    .child(String(i))
    .observeSingleEvent(of: .value, with: { (snapshot) in

        ...

        let nameValue = snapshot.value as? NSDictionary

        if nameValue != nil {

            user.id = String(i)
            // prints the item number
            print(counter)

        }
        // increment the counter when you actually have data
        counter += 1

    }) { (error) in

        print(error.localizedDescription)

}

i += 1

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM