Objects viewing - UICollectionView

2019-08-08 14:58发布

I am trying to add objects to an array in order to view them using UICollection View. I am using this code using Firebase:

// Retrieve the products and listen for changes
    databaseHandle = ref?.child("Products").observe(.childAdded, with:
    { (snapshot) in

        // Code to execute when new product is added
        let prodValue = snapshot.value as? NSDictionary
        let prodName = prodValue?["Name"] as? String ?? ""
        let prodPrice = prodValue?["Price"] as? Double ?? -1
        let prodDesc = prodValue?["Description"] as? String ?? ""

        var prodToAddToView = Product(name: prodName, price: prodPrice, currency: "USD", description: prodDesc, location: "USA")
        self.products.append(prodToAddToView)
    })

But when the loop is done, no objects are shown. On the other hand, using this code :

var pr = Product(name: "a", price: 3, currency: "3", description: "SDF", location: "ASD")
    products.append(pr)

The object is shown in the UICollectionView. If I add more products the same way I did in the 2nd method, they are shown as well. What am I missing ? Is adding an object inside the scope doesn't effect the array outside?

Also - while debugging, I saw the prodToAddToView in the observe function there is created fine.

products is of type [Products]

EDIT:

This code is in my "ViewDidLoad" function, as I want to load all the products before view loads.

1条回答
做个烂人
2楼-- · 2019-08-08 15:24

You need to update your collectionView addself.collectionView.reloadData() in main thread below self.products.append(prodToAddToView)

    DispatchQueue.main.async {
        self.collectionView.reloadData()
    }

Full code

databaseHandle = ref?.child("Products").observe(.childAdded, with:
{ (snapshot) in

    // Code to execute when new product is added
    let prodValue = snapshot.value as? NSDictionary
    let prodName = prodValue?["Name"] as? String ?? ""
    let prodPrice = prodValue?["Price"] as? Double ?? -1
    let prodDesc = prodValue?["Description"] as? String ?? ""

    var prodToAddToView = Product(name: prodName, price: prodPrice, currency: "USD", description: prodDesc, location: "USA")
    self.products.append(prodToAddToView)
    DispatchQueue.main.async {
        self.collectionView.reloadData()
    }
})
查看更多
登录 后发表回答