在调用下一个方法之前,Firebase没有完成

问题描述 投票:0回答:2

我正在使用以下内容调用firebase数据库:

    let myRef1 = Database.database().reference(withPath: "/tests/\ . 
     (myTest)")
    print(myTest)
    myRef1.observe(.value, with: {
        snapshot in
        print(snapshot)
        var newItems: [qItem] = []
        for item in snapshot.children {
            let mItem = qItem(snapshot: item as! DataSnapshot)
            newItems.append(mItem)
            print(newItems)
        }
        self.myArray = newItems.shuffled()
        print(self.myArray)
    })

    loadNext()
    ...

但是,在进入下一个方法调用之前,它永远不会完成完成处理程序,这取决于此结果。

尝试使它成为一个单独的方法等,但似乎没有任何工作。

swift firebase firebase-realtime-database
2个回答
1
投票

您需要在loadNext()中添加observe方法,以便在检索数据后调用它。当你检索数据时,它是异步发生的,这意味着编译器不会等到检索完所有数据后,它将首先调用方法loadNext(),然后在完成检索数据后它将执行print(newItems),因此你需要执行以下操作:

    myRef1.observe(.value, with: {
    snapshot in
    print(snapshot)
    var newItems: [qItem] = []
    for item in snapshot.children {
        let mItem = qItem(snapshot: item as! DataSnapshot)
        newItems.append(mItem)
        print(newItems)
        loadNext()
    }
    self.myArray = newItems.shuffled()
    print(self.myArray)
})

0
投票

Firebase数据是异步处理的。 Doug Stevenson写了一篇很棒的blog,讲述了为什么这对开发人员意味着什么。我还写了一个blog,其中我展示了如何在函数中使用闭包来处理异步数据。虽然你绝对可以从loadNext()闭包中调用observe,但你可能会发现在同一个函数中你最终会有一长串闭包。我在博客文章中再详细介绍一下。在您的具体情况下,您可以执行以下操作:

func getArray(completion: @escaping ([qtItem]) -> Void) {
  let myRef1 = Database.database().reference(withPath: "/tests/\ . 
     (myTest)")
  print(myTest)
  myRef1.observe(.value, with: {
      snapshot in
      print(snapshot)
      var newItems: [qItem] = []
      for item in snapshot.children {
          let mItem = qItem(snapshot: item as! DataSnapshot)
          newItems.append(mItem)
          print(newItems)
      }
      self.myArray = newItems.shuffled()
      print(self.myArray)
      completion(self.myArray)
  })
}

然后当你调用getArray()时,你可以处理闭包内的数据:

getArray() { newItems in
  // do something with newItems, like pass to `loadNext()` if needed
  self.loadNext()
}
© www.soinside.com 2019 - 2024. All rights reserved.