在 Closure 外访问 Firebase 变量 [英] Access Firebase variable outside Closure

查看:17
本文介绍了在 Closure 外访问 Firebase 变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to use Firebase to set the number of cells in my CollectionView. I tried to create a local variable and set that to the same value as the Firebase variable but when I try use it outside the function it doesn't work. I also tried setting it in ViewWillAppear but it didn't work.

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

I set the nav bar title to view the value. When it was set in the closure I got the correct value, when I wrote that outside the closure (after the firebase function), it gave a value of 0.

我正在使用 swift 3

I'm using 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 返回时才有效.

Firebase is asyncronous and the data is only valid when it's returned from Firebase within the closure.

 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 的数据源.

Expanding from that, suppose we want to populate an array to be used as a dataSource for a 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")
}

请注意,我们从闭包中填充数组,它是一个类 var,一旦填充了该数组,仍然在闭包中,我们刷新 tableView.

Note that we populate the array, which is a class var, from within the closure and once that array is populated, still within the closure, we refresh the tableView.

请注意,print 函数将在填充 tableView 之前发生,因为该代码是同步运行的,并且代码比 Internet 快,因此闭包实际上会在 print 语句之后发生.

Note that the print function will happen before the tableView is populated as that code is running synchronously and code is faster than the internet so the closure will actually occur after the print statement.

这篇关于在 Closure 外访问 Firebase 变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆