Firebase存储数据显示两次

jjhzyzn0  于 2023-05-07  发布在  其他
关注(0)|答案(2)|浏览(134)

尝试使用此方法在集合视图中加载数据

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    if urls.count == 0 {
        return UICollectionViewCell()
    }
    let url = urls[indexPath.item]
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier,
                                                  for: indexPath) as! ImageCollectionViewCell
    storageRef.reference(withPath: url).getData(maxSize: 15 * 1024 * 1024, completion:  { data, error in
            if let data = data {                   
                cell.imageView.image = UIImage(data: data)
            }
        })
    return cell
}

事情是这样的--首先我可以看到两个单元格都没有数据,然后调用completion,我得到一个数据,但是两个单元格中的第一个图像。我怎么能做对呢?我怎么能同时获得元数据呢?
截图:

UPD:
我写了一个数组

var datas = ["first", "second", "third", "fourth"]

已更改的单元格代码

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier,
                                                  for: indexPath) as! ImageCollectionViewCell
    cell.nameLabel.text = datas[indexPath.item]
    return cell
}

得到了这个:

还是看不出哪里出了问题我的超控方法:

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

func collectionView(_ collectionView: UICollectionView,
                    numberOfItemsInSection section: Int) -> Int {
    return datas.count / 2
}
yv5phkfx

yv5phkfx1#

我认为问题在于您正在下载 cellForItemAt indexPath: 函数中的信息,而您应该像这样在另一个函数中下载图像

//Variable to store the UIImages
    var images = [UIImage]()

//function to download the images, run it in the viewdidload like self.getImages()
    func getImages(){

        for url in self.urls{

            storageRef.reference(withPath: url).getData(maxSize: 15 * 1024 * 1024, completion:  { data, error in
                if let data = data {
                    self.images.append(UIImage(data: data))
                }
            })
        }

        self.YourCollectionView.reloadData()

    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        if urls.count == 0 {
            return UICollectionViewCell()
        }

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier,
                                                      for: indexPath) as! ImageCollectionViewCell
        cell.imageView.image = self.images[indexPath.row]

        return cell
    }
jecbmhm3

jecbmhm32#

numberOfSection函数应返回1

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

相关问题