Swift - Firebase获取所有密钥并将其存储到阵列中

时间:2022-01-23 21:15:51

I have this firebase Database Structure:

我有这个firebase数据库结构:

Main
----- Name 1
--------value 1
--------value 2
--------value 3
----- Name 2
--------value 1
--------value 1
--------value 1

I'm trying to get all the key values and storing into an array of a custom class.

我正在尝试获取所有键值并存储到自定义类的数组中。

My custom class has an init:

我的自定义类有一个init:

init(name: String, photo: String) {
self._name = name
self._photo = photo
}

So in my View controller I have:

所以在我的View控制器中我有:

var array = [customClass]()
let ref = Database.database().reference().child("Main")

func getInfo(){
    Ref.observeSingleEvent(of: .value) { (snapshot) in
        var arrayTemp = [customClass]()
        for child in snapshot.children {
            let snap = child as! DataSnapshot
            let name = snap.key
            let custom = customClass(Name: name, photo: "")
            arrayTemp.append(custom)
        }
        self.array = arrayTemp
        self.collectionView.reloadData()
    }
}

  func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as? Cell {
        let custom: Custom!
            custom = array[indexPath.row]
            cell.configureCell(custom)
              return cell
    } else {
    return UICollectionViewCell()
    }
}

and here is the cell:

这是细胞:

class Cell: UICollectionViewCell {

@IBOutlet weak var Thumb: UIImageView!
@IBOutlet weak var NameLbl: UILabel!

var custom: CustomClass!


func configureCell(_ custom: customClass) {

    self.custom = custom
    NameLbl.text = self.custom.customName.capitalized
    var url = URL(string: self.custom.photoUrl)
    if url == nil {
        url = URL(string: "")
    }
    Thumb.sd_setImage(with: url)

}

}

}

My issue is that if i print name I have all the values from the Db but when I reload the collection View I see the number of item correct but the name is just the first element repeated x time... Any help?

我的问题是,如果我打印名称我有Db的所有值,但当我重新加载集合视图我看到项目的数量正确,但名称只是重复x时间的第一个元素...任何帮助?

1 个解决方案

#1


1  

To fix your issue :

要解决您的问题:

func numberOfSections(in collectionView: UICollectionView) -> Int {
    return 1
}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return self.array.count
}

#1


1  

To fix your issue :

要解决您的问题:

func numberOfSections(in collectionView: UICollectionView) -> Int {
    return 1
}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return self.array.count
}