如何从Firebase获取图像并将其保存到tableViewCell中的Image?

时间:2018-09-13 15:35:49

标签: swift firebase firebase-storage

我正在使用TableViewController并从Closure中的firebase提取图像。我确实在本地数据库中获得了图像的名称,并在获取时将其保存在数组中。但是,当我使用 indexPath.row 访问图像数组时,所有内容都折叠了(代替我需要的2张图像,所有图像都将被替换,并且在滚动tableView时它会继续增加)。请确实指导我如何获取单元内的图像。预先感谢

var imageList = [UIImage]()
func getData()
    {
        Data = NSMutableArray()
        Data = ModelManager.getInstance().getAllData(planID)
        let count = Data.count
        for i in 0...count-1{
            let demoPlan = (Data.object(at: i) as! workoutPlan)
            ImageDemo.append(demoPlan.Image)

        }
    }


override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

            let cell2:workoutplanCell = tableView.dequeueReusableCell(withIdentifier: "workoutplanCell") as! workoutplanCell
            cell2.planExerciseNameLabel.text = plan.Name

            if(plan.Image.contains("plank")){
                cell2.timerButton.isHidden = false
            }
            else{
                cell2.timerButton.isHidden = true
            }

            var new_imgList = [String]()
            new_imgList.append(ImageDemo[indexPath.row])
            new_imgList.append(ImageDemo[indexPath.row] + "1")

let storage = Storage.storage().reference()

            for x in new_imgList
            {
             let storageRef = storage.child("images/\(new_imgList[x]).jpg")
                storageRef.getData(maxSize: 1 * 1024 * 1024) { (data, error) in
                    if let error = error{
                        print(error.localizedDescription)
                        return
                    }
                    else{
                        self.imageList.append(UIImage(data: data!)!)

                    }
                    if  x == new_imgList{
                        cell2.planExerciseImage.animationImages = self.imageList
                        cell2.planExerciseImage.animationDuration = 2
                        cell2.planExerciseImage.startAnimating()

                        cell2.planDescription.delegate = self
                        cell2.planDescription.text = plan.Description
                        cell2.planDescription.sizeToFit()
                        cell2.planDescription.textColor = UIColor.black
                        self.imageList.removeAll()
                        new_imgList.removeAll()
                    }
                }

            }
           return cell2
        }

1 个答案:

答案 0 :(得分:1)

您可能有此问题的原因有两个: 一种是imageList范围。您已经在ViewController中的某个位置定义了它,每次设置单元格时,它都会不断添加图像。

第二个原因在某种程度上与第一个有关,是if x == 1我看不到该语句一直被调用,因此不会为每个单元格清除您的imageList。 / p>

从声明的地方删除new_imgList,而在此处声明:

for x in new_imgList{

  // DECLARE new_imgList HERE

.....

}

并删除self.imageList.removeAll()行。

相关问题