Re:GCD与Firebase Swift一起更新数据

时间:2016-12-22 17:17:27

标签: ios swift3

我正在尝试填充表格,我从firebase获取了几个不同的数据。我的一个代码如下:

 //Firebase
    let ref = FIRDatabase.database().reference()
    let dataLoad = DispatchGroup()
    let backgroundQ = DispatchQueue(label:"queue", attributes: .concurrent)


    ref.child("Vendor Reviews/\(id)").observeSingleEvent(of: .value, with: { (snapshot) in

        for child in snapshot.children {

            dataLoad.enter()

            backgroundQ.async(group: dataLoad, execute: {

            let snap = child as! FIRDataSnapshot
            let dict = snap.value as? NSDictionary
            let username = dict?["username"] as! String
            let rating = dict?["rating"] as! Double
            let review = dict?["review"] as! String
            let image = dict?["image"] as! String
            let timestamp = dict?["date"] as! TimeInterval

            let rawDate = NSDate(timeIntervalSince1970: timestamp)

            let date = String(describing: rawDate)

            let comment = VendorCommentCellData(img: image, name: username, date: date, comment: review, rating: rating)

            comments += [comment]

            print("Added 1")

                dataLoad.leave()

            })

        }

    })


    dataLoad.notify(queue: DispatchQueue.main){
        print("All added")
    }

出于某种原因,在控制台日志中,打印("全部添加")总是在打印之前出现("添加1")因此,我无法知道我的数据何时被检索,因此根本无法填充我的表格。

我之前在Swift 2中使用了这个,我以同样的方式编写它,但它不起作用。

请告诉我代码出错的地方。我是新手,我对GCD并不擅长。希望你们都能指出我正确的方向。

感谢。

1 个答案:

答案 0 :(得分:0)

let dataLoad = DispatchGroup()
let backgroundQ = DispatchQueue(label:"queue")

backgroundQ.async(group: dataLoad) {
//etc..
}

dataLoad.notify(queue: DispatchQueue.main){
    print("All added")
}