如何将Firebase中的数据正确添加到数组中?

时间:2016-07-10 18:11:31

标签: arrays swift firebase firebase-realtime-database

我正在尝试从Firebase获取结果并将它们放入数组中,但似乎我错过了一些东西。我想要的是从Firebase获取'Time'和'Blood Glucose'值并将它们放入我将用于Charts的数组中。我能够将数据放入'BG'和'TIME'数组,但是当我''追加''FetchedDate'和'FetchedBG'时,我看到空数组(FetchedBG和FetchedDate)

var FetchedDate:[String]! = []
var FetchedBG: [Double]! = []

//GET DATA FROM FB 
func GetDetails(){
    let posts = rootRef.child("Diary/\(userID!)/\(passedDATE!)")
    //let posts = rootRef.queryOrderedByChild(passedDATE!)
    posts.observeEventType(FIRDataEventType.Value , withBlock: { (snapshot) in

        for list in snapshot.children {
            if  let BG = list.value.objectForKey("Blood Glucose")!.doubleValue {
            self.FetchedBG.append(BG)
                print(BG) // SHOWS RESULTS AS EXPECTED
            }
            if let TIME = list.value.objectForKey("Time") {
            self.FetchedDate.append(TIME as! String)
                  print(TIME) // SHOWS RESULTS AS EXPECTED
            }
        }
    })  { (error) in
        print(error.localizedDescription)
    }
}

override func viewDidLoad() {
    super.viewDidLoad()

    GetDetails()

    print(FetchedDate) // EMPTY ARRAY 
    print(FetchedBG) // EMPTY ARRAY 

1 个答案:

答案 0 :(得分:2)

Firebase异步加载(并同步)数据库中的数据。由于这可能需要一些时间,因此您的代码会继续执行,并且在阵列仍然为空时打印它们。

一旦值可用(第一次或数据发生变化),就会调用您的块。它将数据添加到数组中。但到那时你的印刷陈述已经很久了。

解决方案是移动需要在值可用时(或更改时)进入块的代码。 E.g。

var FetchedDate:[String]! = []
var FetchedBG: [Double]! = []

//GET DATA FROM FB 
func StartSynchronizingDetails(){
    let posts = rootRef.child("Diary/\(userID!)/\(passedDATE!)")
    //let posts = rootRef.queryOrderedByChild(passedDATE!)
    posts.observeEventType(FIRDataEventType.Value , withBlock: { (snapshot) in

        for list in snapshot.children {
            if  let BG = list.value.objectForKey("Blood Glucose")!.doubleValue {
            self.FetchedBG.append(BG)
                print(BG) // SHOWS RESULTS AS EXPECTED
            }
            if let TIME = list.value.objectForKey("Time") {
            self.FetchedDate.append(TIME as! String)
                  print(TIME) // SHOWS RESULTS AS EXPECTED
            }
        }
        print(FetchedDate)
        print(FetchedBG)
    })  { (error) in
        print(error.localizedDescription)
    }
}

override func viewDidLoad() {
    super.viewDidLoad()

    StartSynchronizingDetails()

当您的应用与(可能耗时的)网络资源交互时,这是非常的常见模式。这也正是Firebase的observeEventType采用withBlock:参数的原因:从响应值更新的代码中隔离开始同步的代码。