我想只将一些数据从Firebase传递到另一个ViewController。
以下是我的代码。
我已经多次测试但仍然失败了。
我不知道为什么变量 - “限制”在行print(limits) // IT'S EMPTY
上变成空的,我无法将数据成功传递给下一个ViewController。
import UIKit
import Firebase
import FirebaseDatabase
struct limitStruct{
let name : String!
let today : String!
let limit : String!
}
class CalcViewController: UITableViewController {
var limits = [limitStruct]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
navigationController?.navigationBar.barTintColor = UIColor.black
self.title = "Calculation"
navigationController!.navigationBar.titleTextAttributes =
[NSForegroundColorAttributeName: UIColor.white]
let databaseReference = FIRDatabase.database().reference()
databaseReference.child("Limit").queryOrderedByKey().observe(.childAdded, with: {
snapshot in
var snapshotValue = snapshot.value as? NSDictionary
let name = snapshotValue!["name"] as? String
snapshotValue = snapshot.value as? NSDictionary
let today = snapshotValue!["today"] as? String
snapshotValue = snapshot.value as? NSDictionary
let limit = snapshotValue!["limit"] as? String
snapshotValue = snapshot.value as? NSDictionary
self.limits.insert(limitStruct(name:name, today:today, limit: limit), at: self.limits.count)
self.tableView.reloadData()
})
print(limits) // IT'S EMPTY
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return limits.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Limit")
let label1 = cell?.viewWithTag(1) as! UILabel
label1.text = limits[indexPath.row].name
let label2 = cell?.viewWithTag(2) as! UILabel
label2.text = limits[indexPath.row].today
return cell!
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showDetails"{
let svc = segue.destination as! CirSliderViewController;
if let indexPath = self.tableView.indexPathForSelectedRow{
let segueData : limitStruct
segueData = limits[indexPath.row]
svc.RsegueData = segueData
}
}
}
}
答案 0 :(得分:1)
databaseReference.child("Limit").queryOrderedByKey().observe()
异步执行一段代码。这意味着当调用print(limits)
时,它尚未运行,因此限制为空。