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

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

问题描述

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

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

I 'm使用swift 3

 重写func viewWillAppear(_ animated:Bool){

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

如果让snapInt = snapshot.value as? Int {


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


}










$ self_navigationItem.title = String(numCells)


code











  override func collectionView(_ collectionView:UICollectionView,numberOfItemsInSection section:Int) - > Int {
// #warning不完整的实现,返回项目数


返回numCells

}

引用(withPath:data)。child(numCells)
.observeSingleEvent()。

  FIRDatabase.database .value:{snapshot in 
如果让snapInt = snapshot.value as?Int {
self.navigationItem.title = String(snapInt)
}
})

从这个扩展中,假设我们想要填充一个数组作为tableView的一个数据源。

  class ViewController:UIViewController {
//定义tableView或集合或某种类型的列表
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 (这将填充之前,tableView被填充)
}

请注意,我们填充这个数组是一个类var,在这个闭包中,一旦这个数组被填充,仍然在闭包内,我们刷新tableView。



注意print函数会在tableView被填充之前发生,因为代码是同步运行的,代码比互联网更快关闭实际上会在打印语句后发生。


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.

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.

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

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

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.

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天全站免登陆