IOS - 从Firebase解析对象 - 在下载完成之前运行的代码

时间:2016-09-02 18:47:36

标签: swift parsing asynchronous firebase completionhandler

我正在尝试将Firebase中的数据解析为一个对象数组,并在完成后显示数组中第一个对象的文本。但是,在下载完成之前,我无法找到解决方案来停止代码。因此,它继续将用户的完成更新为true,而不显示文本。这是函数原样,下载和附加到数组工作正常,但它在完成之前会跳到displayNextInSeries()...

    func parseSeries (ref: String)  {
    FIRDatabase.database().reference().child("library").child("series").child(ref).observeSingleEvent(of: .value, with:  { (snapshot)  in

        if let snapshot = snapshot.children.allObjects as? [FIRDataSnapshot] {

            for snap in snapshot {

                print(snap)

                if let pushSeriesDict = snap.value as? Dictionary<String, AnyObject> {
                    let key = snap.key
                    let push = PUSH_SERIES(pushKey: key, pushSeriesData: pushSeriesDict)
                    self.seriesArray.append(push)

                }
            }
        }
    })

    print("\(ref) Series Count: \(self.seriesArray.count)")
    displayNextInSeries()

}

系列函数中的下一个显示看到seriesArray.count = 0,因此它不会更新texLbl:

   func displayNextInSeries() {

    if seriesProgress < seriesArray.count {

        animateProgress(current: seriesProgress, total: seriesArray.count)

        currentPUSH_SERIES = seriesArray[seriesProgress]
        currentPUSH_SERIES.text = personaliseText(text: currentPUSH_SERIES.text)

        textLbl.animateUpdate(currentPUSH_SERIES.text, oldText: previousText)
        titleLbl.text = "\(currentPUSH_SERIES.title!)"
        previousText = currentPUSH_SERIES.text

        seriesProgress += 1

    } else {

        animateProgress(current: sessionProgress, total: sessionTarget)

        titleLbl.text = ""
        greetingPush()
        seriesPlay = false
        seriesProgress = 0

        user.updateProgress(seriesName)
        print(user.progress)


    }

}

我可能在这里做了一些根本错误的事情。非常需要您的帮助,非常感谢!谢谢,马特

1 个答案:

答案 0 :(得分:1)

observeSingleOfEvent是一个异步调用,调用completionBlock中的函数将解决它,问题是即使在observeSingleOfEvent下载数据之前你的打印函数也被调用: -

func parseSeries (ref: String)  {
FIRDatabase.database().reference().child("library").child("series").child(ref).observeSingleEvent(of: .value, with:  { (snapshot)  in

    if let snapshot = snapshot.children.allObjects as? [FIRDataSnapshot] {

        for snap in snapshot {

            print(snap)

            if let pushSeriesDict = snap.value as? Dictionary<String, AnyObject> {
                let key = snap.key
                let push = PUSH_SERIES(pushKey: key, pushSeriesData: pushSeriesDict)
                self.seriesArray.append(push)
                print("\(ref) Series Count: \(self.seriesArray.count)")
                displayNextInSeries()
            }
        }
    }
  })
}