将Aync Gif加载到滚动CollectionView

时间:2019-05-15 23:44:15

标签: ios swift asynchronous uicollectionview gif

我从Giphy API获取的gif可以正确返回,并且实际上可以使用uicollectionview正确地加载到SwiftGif

该问题仅在我立即滚动时出现,uicollectionview加载重复的gif或索引不正确的gif。我了解这可能是一个时序问题,因为渲染gif和将gif加载到单元格的延迟。

任何指导都会受到赞赏,因为异步操作是我仍然不熟悉的东西。

如果下面的代码中有任何标志,特别是为了支持速度/内存使用,则任何处理gif的最佳做法也将受到赞赏。

我尝试过各种检查,例如查看最初传递的gif URL在加载时是否相同,并且每次触发cellForItemAt时都将图像设置为nil,但无济于事。找不到也可以清楚解决此问题的现有线程。

class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {

@IBOutlet weak var gifCollectionView: UICollectionView!

var gifUrls: [String] = []
var gifImages: [String: UIImage] = [:]

func fetchGiphs() {
    let op = GiphyCore.shared.search("dogs", media: .sticker) { (response, error) in

        guard error == nil else {
            print("Giphy Fetch Error: ", error)
            return
        }

        if let response = response, let data = response.data, let pagination = response.pagination {
            for result in data {
                if let urlStr = result.images?.downsized?.gifUrl {
                    self.gifUrls.append(urlStr)
                }
            }
            if !self.gifUrls.isEmpty {
                DispatchQueue.main.async {
                    self.gifCollectionView.reloadData()
                }
            }
        } else {
            print("No Results Found")
        }
    }
}

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

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! GifCell

    let passedUrlString = gifUrls[indexPath.item]
    cell.imageView.image = nil

    if let image = gifImages[gifUrls[indexPath.item]] {
        DispatchQueue.main.async {
            cell.imageView.image = image
            cell.activityIndicator.isHidden = true
        }
    } else {
        cell.activityIndicator.isHidden = false
        cell.activityIndicator.startAnimating()
        DispatchQueue.global(qos: .default).async {
            let gifImage = UIImage.gif(url: self.gifUrls[indexPath.item])
            DispatchQueue.main.async {
                if passedUrlString == self.gifUrls[indexPath.item] {
                    cell.activityIndicator.stopAnimating()
                    cell.activityIndicator.isHidden = true
                    cell.imageView.image = gifImage
                    self.gifImages[self.gifUrls[indexPath.item]] = gifImage
                }
            }
        }
    }

    return cell
}
}


class GifCell: UICollectionViewCell {
    @IBOutlet weak var imageView: UIImageView!
    @IBOutlet weak var activityIndicator: UIActivityIndicatorView!
}

1 个答案:

答案 0 :(得分:1)

如您所知,图像加载完成后,该单元可能会被重用。

您需要检查它是否被重复使用。您的passedUrlString == self.gifUrls[indexPath.item]不适用于此目的。

也许,为每个单元格提供唯一的ID会起作用:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! GifCell
    let uniqueId = Int.random(in: Int.min...Int.max) //<-practically unique
    cell.tag = uniqueId //<-

    cell.imageView.image = nil

    if let image = gifImages[gifUrls[indexPath.item]] {
        cell.imageView.image = image
        cell.activityIndicator.isHidden = true
    } else {
        cell.activityIndicator.isHidden = false
        cell.activityIndicator.startAnimating()
        DispatchQueue.global(qos: .default).async {
            let gifImage = UIImage.gif(url: self.gifUrls[indexPath.item])
            DispatchQueue.main.async {
                if cell.tag == uniqueId { //<- check `cell.tag` is not changed
                    cell.activityIndicator.stopAnimating()
                    cell.activityIndicator.isHidden = true
                    cell.imageView.image = gifImage
                    self.gifImages[self.gifUrls[indexPath.item]] = gifImage
                }
            }
        }
    }

    return cell
}

假设您没有将tag用于其他目的。

请尝试。