【问题标题】:the images keep on changing after getting loaded from firebase in the simulator从模拟器中的firebase加载后,图像不断变化
【发布时间】:2018-12-17 19:59:41
【问题描述】:

我有一个跟随视图控制器,其中嵌入了一个表格视图控制器。 当我尝试从 Firebase 加载配置文件图像时,它加载良好,但在向下或向上滚动时会继续与其他配置文件图像交换图像。 此外,当我点击表格视图单元格以关注该特定用户时,指示(复选标记)也会出现在第四个单元格上。 这是xcode中的错误吗 我在 Mac os sierra 10.12.6 上使用 Xcode 9.1

【问题讨论】:

  • 过去你的代码,以便其他人可以帮助识别问题

标签: ios xcode firebase firebase-storage


【解决方案1】:

如果您从背景中获取图像,请确保将每个图像分配给正确的单元格。一种方法是创建一个包含图像和唯一 id 的自定义类,每当您想将图像分配给单元格时,请先检查 id 以确保它是正确的。

关于勾号bug,你可以尝试在prepareForReuse()函数内重置单元格。

编辑

由于您使用的是异步,因此无法保证图像会按顺序返回。因此,要将正确的图像放入正确的单元格中,您需要执行以下操作

//if the image is already fetched, you don't have to get it from firebase again
private var imageCache = [String:UIImage]()

//Create custom ImageView class that downloads image from url 
class CustomImageView: UIImageView{

var lastImageURL: String?

//call this function to get the right image with url
func setupWithImageURL(imageURL: String){
    self.contentMode = .scaleAspectFill
    self.clipsToBounds = true

    //keep track of the url of the right image
    lastImageURL = imageURL

    //check if the image is already there
    if let cachedImage = imageCache[imageURL]{
        self.image = cachedImage
        return
    }

    //if no image, get it with url
    guard let url = URL(string: imageURL) else {return}

    URLSession.shared.dataTask(with: url) { (data, response, err) in
        if let err = err{
            print("Unable to download data from database: ",err)
            return
        }

        guard let data = data else {return}
        guard let image = UIImage(data: data) else {return}
        imageCache[url.absoluteString] = image

        //if not the correct image, return and do nothing
        if (url.absoluteString != self.lastImageURL){
            return
        }

        //if the image is the correct one, set it to the imageView
        DispatchQueue.main.async {
            self.image = image
        }
    }.resume()
}

}

【讨论】:

  • 在我真正满意并继续进行项目的其余部分之前,它运行良好。我将它的初始视图控制器更改为我想要使用的视图控制器。但是几天后,当我从头开始重新运行我的应用程序时,我遇到了这个问题。早些时候,我通过干净地重写代码来解决这个问题并且它起作用了(在这个问题中也出现了一段时间后)。我已经用代码更新了我的问题
  • 我用代码编辑了我的评论。希望它能解决你的问题! @user00007
  • 哇!图像现在看起来很完美,但是。当我向下滚动时,我仍然注意到一些数据正在下载。复选标记也出现在另一个单元格中。
  • 是因为tableView复用单元格的方式。使用set 的复选标记来跟踪您手动放置复选标记的单元格。在cellForRowAtIndexPath中,如果cell indexPath不在集合中,则更改附件类型。
猜你喜欢
  • 2016-10-16
  • 1970-01-01
  • 1970-01-01
  • 2015-11-12
  • 2013-01-22
  • 2021-10-26
  • 2010-12-23
  • 1970-01-01
  • 2015-02-02
相关资源
最近更新 更多