gpt4 book ai didi

ios - 如何使用 Firebase 更改我的值

转载 作者:行者123 更新时间:2023-11-29 00:51:58 25 4
gpt4 key购买 nike

我的代码给了我一个无限循环,他永远不会进入 if 或 else,我很确定,因为 firebase 只获取异步函数。
我想检查“random_hexa”是否存在,并获取新的随机数,直到我得到一个不存在于我的数据库中的值

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
}
})

最佳答案

您正在运行一个本地 while 循环,该循环无法处理 Firebase 数据库(以及大多数现代互联网)的异步性质。正确的流程是:

  1. 生成一个随机值
  2. 开始调用数据库以查看该值是否已存在
  3. 等待调用完成
  4. 如果该值尚不存在,请高兴
  5. 否则重新开始

这可以通过递归函数最轻松地完成:

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)
}
})
}

然后你称之为:

findUniqueNumber(ref, withBlock: { value in
print(value)
})

关于ios - 如何使用 Firebase 更改我的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38030619/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com