Swift 3 - 在阵列中保存Firebase数据

时间:2017-04-27 13:47:25

标签: ios swift firebase viewcontroller

我正在尝试将Firebase数据保存在数组中,但数组计数每次都是0。

override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)

        getAllSkateShops()
}


func getAllSkateShops() {

        ref = FIRDatabase.database().reference()

        ref.child("Shops").observeSingleEvent(of: .value, with: { (snapshot) in

            //var newShops: [SkateShop] = []

            for item in snapshot.children {

                let skateShopItem = SkateShop(snapshot: item as! FIRDataSnapshot)
                self.shops.append(skateShopItem)
                DispatchQueue.main.async(execute: {
                  print("OBSERVE SHOP COUNT: \(self.shops.count)")
                })
            }

        })
}

在函数viewDidLoad()中,self.shop.count为零,但我需要所有商店的数组。

我希望有人可以帮助我;)

1 个答案:

答案 0 :(得分:0)

我遇到了同样的问题,idk为什么会这样,但是在DispatchQueue.main.async做(编辑):

func getAllSkateShops() {

    ref = FIRDatabase.database().reference()

    ref.child("Shops").observeSingleEvent(of: .value, with: { (snapshot) in

        //var newShops: [SkateShop] = []

        for item in snapshot.children {

            let skateShopItem = SkateShop(snapshot: item as! FIRDataSnapshot)
            self.shops.append(skateShopItem)
            self.shops2.append(skateShopItem)
            DispatchQueue.main.async(execute: {
                var temporaryArray = self.shop2
                self.shop = temporaryArray
            })
        }

    })
}

如果这不起作用,我会给出另一种可能有用的选项。