繁体   English   中英

Firebase While Loop迅捷4

[英]Firebase While Loop Swift 4

我正在其中一个应用程序中创建一个新页面,并且遇到了一个涉及Firebase和While循环的小问题。 下面是我的代码:

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

}

日志:

打印声明1:

0
1
2
3
4
etc.

打印声明2:

101
101
101
101
101
etc.

我在这里唯一的问题是为什么第二个打印语句总是打印101,而不是i的增量值。 这与Firebase Observer不会在每次执行while循环时都观察单个事件有关吗? 另外,我该怎么做才能解决此问题?

谢谢,KPS

这是因为firebase异步查询您的请求,而完成处理程序(您在其中打印i )则恰好在while循环结束且i的值为101时被调用。

编辑:一种解决方法是拥有一个单独的计数器,仅在检查值时才递增。 因此,只有当结果输入并且您可以知道哪个结果为零时,这种情况才会改变。 但是,这并不可靠,因为网络请求可能很慢且无序,但在大多数情况下应该可以正常工作

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