Swift + Firebase在didFinishLaunchingWithOptions中预加载数据

时间:2016-08-27 07:34:38

标签: swift firebase firebase-realtime-database

我正在实施一个从Firebase中提取数据的tableview。我的tableview分为动态依赖于Firebase中的条目的部分,并且在viewdidload中检索数据会使应用程序崩溃。

如何在viewdidload之前从didFinishLaunchingWithOptions中的Firebase中提取数据?这个tableview是我的第一个视图控制器。

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    FIRApp.configure()
    return true
}

//在tableview控制器中

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
}

1 个答案:

答案 0 :(得分:0)

好的,你可以选择全局变量。而不是声明变量" date"在MyTableViewController内,您可以将其声明为全局变量。

public var dates: [(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

时获得数据
相关问题