简体   繁体   English

Firebase While Loop迅捷4

[英]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. 我正在其中一个应用程序中创建一个新页面,并且遇到了一个涉及Firebase和While循环的小问题。 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 : 打印声明1:

0
1
2
3
4
etc.

Print Statement 2: 打印声明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. 我在这里唯一的问题是为什么第二个打印语句总是打印101,而不是i的增量值。 Is this something related to the Firebase Observer not observing the single event every time the while loop is executed? 这与Firebase Observer不会在每次执行while循环时都观察单个事件有关吗? Also, what can I do to fix this? 另外,我该怎么做才能解决此问题?

Thanks, KPS 谢谢,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. 这是因为firebase异步查询您的请求,而完成处理程序(您在其中打印i )则恰好在while循环结束且i的值为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

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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