错误:从firebase快照中检索数据时索引超出范围

时间:2017-06-24 20:35:09

标签: 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)")
            }

1 个答案:

答案 0 :(得分:0)

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

所以你应该以这种方式使用它

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