Access Firebase variable outside Closure

后端 未结 1 1496
日久生厌
日久生厌 2020-11-28 17:00

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 w

相关标签:
1条回答
  • 2020-11-28 17:29

    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.

    0 讨论(0)
提交回复
热议问题