Firebase存储数据显示两次

时间:2017-07-17 00:10:49

标签: ios swift firebase firebase-storage

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

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
}

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

截图:

Screenshot:

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
}

得到了这个:

enter image description here

仍然看不出有什么问题。我的主要方法是:

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

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

解决。应该返回numberOfSections = 1

2 个答案:

答案 0 :(得分:0)

我认为问题是你要在 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
    }

答案 1 :(得分:0)

应该在numberOfSection函数中返回1

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

}