swift - 在Closure外部訪問Firebase變量
firebase-realtime-database uicollectionview (1)
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的dataSource。
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。
請注意,打印函數將在填充tableView之前發生,因為該代碼同步運行且代碼比Internet快,因此閉包將實際發生在print語句之後。
我正在嘗試使用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
}