将Firebase数据保存在

将Firebase数据保存在

我正在尝试将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为零,但我需要所有Shops都使用此数组。

我希望有人能帮助我;)

最佳答案

我有同样的问题,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
            })
        }

    })
}


如果这不起作用,请发表评论,我将提供另一个可行的选择。

08-26 03:30