Swift 3 UICollectionViewCell异步加载图像GIF

时间:2018-01-05 11:54:58

标签: swift swift3 swift4 xcode9

我正在从GIPHY API加载Gif,事实是Gifs加载得很好但是当我快速滚动时出现错误,它会在瞬间T开始加载GIF我开始滚动并重新使用单元格。我想确保只能为他的专用单元加载一个gif。 实际上,它加载了错误的一个和重新上传的TIME,好的gif覆盖了错误,但是需要1-2s,具体取决于连接,gif大小。这对客户体验来说是不可接受的。

这是我的代码:

    import Foundation
    import UIKit
    import FLAnimatedImage
    import KFSwiftImageLoader
    import PitPutSDK

    open class GifManager: NSObject, UICollectionViewDelegateFlowLayout, UICollectionViewDataSource {
var controller: ConversationViewController
var collectionView: UICollectionView
var client = Config.clientGiphy
var trendsGif = [String?](repeating: "https://i0.wp.com/jenrose.com/wp-content/uploads/2016/11/mourning.jpg?w=256", count: 25)
var widthGif = [Int](repeating: 1000, count: 25)
var actualGifInput: String = ""

init(controller: ConversationViewController, collectionView: UICollectionView) {
    self.controller = controller
    self.collectionView = collectionView

    super.init()

    self.collectionView.register(UINib(nibName: "gifCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "gifCollectionViewCell")
}

public func sendTextForGifSearch(search: String? = "") {
    print("sendTextForGifSearch")
    guard let willFetchedSearch = search else {
        self.actualGifInput = ""
        return
    }
    self.actualGifInput = willFetchedSearch
    self.getTrendsGif(search: willFetchedSearch, limit: 25)
}

public func getTrendsGif(search: String? = "", limit: Int) {
    guard let fetchedSearch = search else {
        return
    }
    print("GET trends, for search \(String(describing: search))")
    if fetchedSearch != "" {
        let _ = client.search(fetchedSearch, limit: limit) { (response, error) in
            if let error = error as NSError? {
                print("Error \(error.localizedDescription) while loading Giphy Trends")
            }
            var i = 0
            if let response = response, let data = response.data {
                for result in data {
                    guard let gifURLs = result.images?.fixedHeightSmall?.gifUrl,
                        let gifWidths = result.images?.fixedHeightSmall?.width else {
                            print("No URL on response")
                            return
                    }
                    QueueManager.globalMainQueue.async {
                        self.trendsGif[i] = gifURLs
                        self.widthGif[i] = gifWidths
                        self.collectionView.reloadData()
                        i += 1
                    }
                }
            }
        }
    } else {
        let _ = client.trending(limit: limit) { (response, error) in

            if let error = error as NSError? {
                print("Error \(error.localizedDescription) while loading Giphy Trends")
            }

            var i = 0
            if let response = response, let data = response.data {
                for result in data {
                    guard let gifURLs = result.images?.fixedHeightSmall?.gifUrl,
                    let gifWidths = result.images?.fixedHeightSmall?.width else {
                        print("No URL on response")
                        return
                        }
                    QueueManager.globalMainQueue.async {
                        self.trendsGif[i] = gifURLs
                        self.widthGif[i] = gifWidths
                        self.collectionView.reloadData()
                        i += 1
                    }
                }
            } else {
                print("No Results Found")
            }
        }
    }
}

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

public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    print("Cell for Item AT \(indexPath)")
    print("Gifs : \(trendsGif)")

    let cell = self.collectionView.dequeueReusableCell(withReuseIdentifier: "gifCollectionViewCell", for: indexPath) as! gifCollectionViewCell

    if let toPrintGif = trendsGif[indexPath.row] {
        if let gifURL: URL = (URL(string: toPrintGif)) {
            cell.gifView.animatedImage = nil

            QueueManager.chatPageDataSource.async {
                //cell.gifView.animatedImage = nil
                let gifData = try? Data(contentsOf: gifURL)
                cell.gifView.animatedImage = FLAnimatedImage(gifData: gifData)

            }
        }

    }
    return cell
}

public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    return CGSize(width: widthGif[indexPath.row], height: 100)
}

public func collectionView(_ collectionView: UICollectionView,
                           layout collectionViewLayout: UICollectionViewLayout,
                           insetForSectionAt section: Int) -> UIEdgeInsets {
    return UIEdgeInsets(top: 0.0, left: 0.0, bottom: 0.0, right: 0.0)
}

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

}

0 个答案:

没有答案