我正在实现一个从 Firebase 中提取数据的 TableView 。我的 tableview 分为多个部分,这些部分动态依赖于 Firebase 中的条目,并且在 viewdidload 中检索数据会使应用程序崩溃。
如何在 viewdidload 之前在 didFinishLaunchingWithOptions 中从 Firebase 中提取数据?这个 TableView 是我的第一个 View Controller 。
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
FIRApp.configure()
return true
}
//在 TableView Controller 中
class MyTableViewController: UITableViewController {
var ref: FIRDatabaseReference!
private var _refHandle: FIRDatabaseHandle!
var mileageDatabase: [FIRDataSnapshot]! = []
var dates: [(String)] = []
override func viewDidLoad() {
super.viewDidLoad()
print("View did load \(self.dates)")
configureDatabase()
self.tableView = UITableView(frame: self.tableView.frame, style: .Grouped)
}
func configureDatabase() {
ref = FIRDatabase.database().reference()
_refHandle = self.ref.child("mileage").observeEventType(.ChildAdded, withBlock: { (snapshot) in
self.mileageDatabase.append(snapshot)
self.tableView.insertRowsAtIndexPaths([NSIndexPath(forRow: self.mileageDatabase.count - 1, inSection: 0)].reverse(), withRowAnimation: .Automatic)
})
self.ref.child("mileage").queryOrderedByChild("date").observeEventType(.ChildAdded, withBlock: { (snapshot) in
print(snapshot.value?["date"])
self.dates.append(snapshot.value?["date"] as! String)
// Here I will do some magic to sort out unique dates
})
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return self.dates.count
}
最佳答案
好的,您可以使用全局变量。您可以将其声明为全局变量,而不是在您的 MyTableViewController
中声明变量“dates”。
公共(public)变量日期:[(String)] = []
。
代码应该在任何类的范围之外
现在将以下代码移动到 func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool
ref = FIRDatabase.database().reference()
ref.child("mileage").queryOrderedByChild("date").observeEventType(.ChildAdded, withBlock: { (snapshot) in
print(snapshot.value?["date"])
dates.append(snapshot.value?["date"] as! String)
// Here I will do some magic to sort out unique dates
})
您将在 viewDidLoad
时拥有您的数据
关于Swift + Firebase 在 didFinishLaunchingWithOptions 中预加载数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39178661/