ios - 错误 : index out of range when retriveing data from firebase snapshot

标签 ios swift firebase

我有正常的 firebase 获取数据方法,但是在附加数据并从快照函数调用该函数后,我的应用程序崩溃了,但是当它在快照函数内部时,该过程成功了,这是我的代码:

var randumUserKey: String = ""
var counterKey: Int = 0
var counter = 0
var keys = [String]()


Database.database().reference().child("posts").observe(.value, with: { (snapshot) in
            for a in ((snapshot.value as AnyObject).allKeys)!{
                self.keys.append(a as! String)
              //  self.keys2.append(a as! Int)
               // print(a)
            }
            print("KKEeeys")
            print(self.keys)

        })
        func generateNum(){

                self.randumUserKey = self.keys[self.counter] //this is the error highlighted in red color in xCode
                self.counter += 1

                if self.counter == self.keys.count{
                    self.counter = 0
                    print("counter == 0 now!")
                }

               print("the number is \(self.counter)")
            }

最佳答案

firebase 函数是一个异步函数。也就是说,当您调用 Database.database().reference().child("posts").observe() 方法时,您正在向 firebase 服务器发送请求以在后台请求数据,然后如果您在服务器调用之后立即调用 generateNum(),您的 key 中将没有任何内容。服务器请求比运行下一行代码要慢得多。

所以你应该这样使用它

Database.database().reference().child("posts").observe(.value, with: { (snapshot) in
    for a in ((snapshot.value as AnyObject).allKeys)!{
        self.keys.append(a as! String)
        print (a + " added")
    }
    self.generateNum()
})

关于ios - 错误 : index out of range when retriveing data from firebase snapshot,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44740760/

相关文章:

ios - 快速获取特定时间之间的位置

ios - react-native 启动 setup_env.sh 的 EACCESS 错误

ios - UIDevice 设置方向在 iPad 上不起作用

firebase - 我需要保护我的 firebase 服务器 key 吗?我可以将它存储在源代码中还是有办法以编程方式获取它?

javascript - 使用 GWT 时未找到 Firebase Service Worker(404 错误)

android - Firebase functions.https.onCall 有效但返回 null

ios - iOS 中的 InMobi 广告集成

ios - 登录到 Facebook 评论 iOS (swift) 没有响应

ios - 对泛型类型使用算术运算符(+、-、/、*)

swift - 在 Mac 上运行脚本提示 Error?