在CollectionView Swift上显示Gif

时间:2018-09-18 20:56:55

标签: ios swift uicollectionview gif

我的收藏夹视图不使用GIPHY ..和SwiftGif Extension显示gifs.im,而是在UIImageView上显示gifs ...这是代码

func searchGif(search: String) {
    GiphyCore.configure(apiKey: "hRuR15WOxvhonLAsLhd0R8pDGvJxQYOk")
    respondView.isHidden = true
    _ = GiphyCore.shared.search(search, media: .gif, offset: 2, limit: 6, rating: .ratedG, lang: .english, completionHandler: { [weak self] (response, error) in
        self?.isDataLoading = false
        if let error = error {
            print("error in response", error)
        }
        guard
            let data = response?.data else { return }
        self?.initialize()
        for results in data {
            let urlString = results.url
            guard let url = URL(string: urlString) else { return }
            do {
                let data = try Data(contentsOf: url)
                let foundedGif = GifModel(gifUrl: data, urlString: urlString)
                self?.gifModel.append(foundedGif)
            } catch let error as NSError {
                print(error)
            }
        }
        if self?.gifModel.isEmpty ?? false {
            self?.setupNofound()
        }
        DispatchQueue.main.async {
            self?.gifCollectionView.reloadData()
        }
    })
}

在集合视图的代表中...

func collectionView(_ collectionView: UICollectionView,
                    cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    guard let cell = collectionView.dequeueReusableCell(
        withReuseIdentifier: GifSearchCollectionViewCell.identifier,
        for: indexPath
        ) as? GifSearchCollectionViewCell else {
            return UICollectionViewCell()
    }
    cell.gifModel = gifModel[indexPath.row]
    return cell
}

以及numberOfItems in sections中的.....

我把gifModel.count的数据很好地工作了,我对数组模型中的6有一个响应...

并在单元格中:

@IBOutlet weak var splashGifView: UIImageView!
var gifModel: GifModel? {
    didSet {
        guard
            let gif = gifModel?.gifUrl else { return }
        splashGifView.image = UIImage.gifImageWithData(gif)
    }
}

我尝试使用String,但是什么也没有,单元格已经创建,但是不显示gifs……有人可以提供帮助吗?

更新...

       @IBOutlet weak var splashGifView: UIImageView!
var gifModel: GifModel? {
    didSet {
        guard let gif = gifModel? { return }
        let url = gif.gifUrl. // <- this give nill
        splashGifView.image = UIImage.gifImageWithData(url)  
    }
}

URL无效,但是在我的模型中,数据URL正确...

1 个答案:

答案 0 :(得分:0)

我发现了!.. GIPHY,有一个非常“入站”的结构,我在响应中得到了图像Gif,就像这样。...

results.images?.original?.gifURL

     for results in data {
           let newGif = GifModel(gifUrl: results.images?.original?.gifUrl ?? "", run: false)     
           self?.gifModel.append(newGif)
     }

现在,我可以获取带有扩展名“ .GIF”的URL,并且该SwiftGif可以在集合中显示查看gifs ...