在 Closure 之外访问 Firebase 变量

Access Firebase variable outside Closure

我正在尝试使用 Firebase 设置 CollectionView 中的单元格数量。我试图创建一个局部变量并将其设置为与 Firebase 变量相同的值,但是当我尝试在函数外部使用它时它不起作用。我也尝试在 ViewWillAppear 中设置它,但它没有用。

我设置了导航栏标题来查看值。当它在闭包中设置时,我得到了正确的值,当我在闭包外写它时(在 firebase 函数之后),它给出了 0 的值。

我正在使用 swift 3

override func viewWillAppear(_ animated: Bool) {

        FIRDatabase.database().reference(withPath: "data").child("numCells").observeSingleEvent(of: .value, with: { (snapshot) in

            if let snapInt = snapshot.value as? Int {


               // self.navigationItem.title = String(snapInt)
                self.numCells = snapInt


            }

        }) { (error) in
            print(error.localizedDescription)
        }

        self.navigationItem.title = String(numCells)

    }

...

 override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of items


       return numCells

    }

Firebase 是异步的,数据只有在闭包内从 Firebase 返回时才有效。

 FIRDatabase.database().reference(withPath: "data").child("numCells")
                      .observeSingleEvent(of: .value, with: { snapshot in
      if let snapInt = snapshot.value as? Int {
           self.navigationItem.title = String(snapInt)
      }
 })

由此展开,假设我们要填充一个数组以用作 tableView 的数据源。

class ViewController: UIViewController {
    //defined tableView or collection or some type of list
    var usersArray = [String]()
    var ref: FIRDatabaseReference!

     func loadUsers() {
          let ref = FIRDatabase.database().reference()
          let usersRef = ref.child("users")

          usersRef.observeSingleEvent(of: .value, with: { snapshot in
              for child in snapshot {
                  let userDict = child as! [String: AnyObject]
                  let name = userDict["name"] as! string
                  self.usersArray.append[name]
              }
              self.myTableView.reloadData()
          })
     }
     print("This will print BEFORE the tableView is populated")
}

请注意,我们从闭包中填充数组,它是一个 class var,一旦该数组被填充,仍在闭包中,我们刷新 tableView。

请注意,打印函数将在填充 tableView 之前发生,因为该代码是 运行 同步并且代码比互联网更快,因此关闭实际上将发生在打印语句之后。