【问题标题】:GIF images to UIImageView using AlamofireImage in Swift在 Swift 中使用 AlamofireImage 将 GIF 图像转换为 UIImageView
【发布时间】:2018-09-21 09:41:20
【问题描述】:

我正在使用 AlamofireImage 库来下载/缓存网络图像并将其显示在 tableViewCells 内的 UIImageView 中。

imageView.af_setImage(withURL: url, placeholderImage: nil, filter: nil, imageTransition: .crossDissolve(0.3), runImageTransitionIfCached: true, completion: { (response) in
//...... other code .....
})

它非常适合 .png/.jpg 或其他静止图像,但我无法使用它显示 GIF 图像。

我尝试使用外部库将 imageData 转换为 gif 图像,并且效果很好,但是 Alamofire 没有缓存 gif 数据,并且下次图像加载为静止图像。

检查下面的代码:

imageView.af_setImage(withURL: url, placeholderImage: nil, filter: nil, imageTransition: .crossDissolve(0.3), runImageTransitionIfCached: true, completion: { (response) in

        if imageUrl.hasSuffix("gif") {
            if let data = response.data{
                self.imageView.image = UIImage.gifImageWithData(data)
            }
        }
    })

上面的代码第一次显示GIF,但下一次只显示静止图像。

知道如何使用 AlamofireImage 实现以下目标:

  1. 第一次下载GIF imageData,缓存并显示GIF到imageView

  2. 下次从缓存中获取imageData并再次显示GIF

【问题讨论】:

  • 这里是使用 Gif Image 的最佳解决方案。在您的项目中添加来自 Github 的 SDWebImage。 SDWebImage Github 链接:github.com/rs/SDWebImage
  • 为此使用 SDWebImage 库。这也是最好的缓存。
  • AlamofireImage 可以做到这一点吗?我不想为了同样的目的向项目中添加另一个库。

标签: ios swift uiimageview gif alamofireimage


【解决方案1】:

我还没有找到使用 AlamofireImage 播放 GIF 的直接方法,但我们可以使用 SwiftyGif。我在整个应用程序中使用 AlamofireImage,但为了显示 GIF 和从服务器加载,我使用的是 SwiftyGif。使用 SwiftyGif,您可以从服务器和本地播放、加载。我认为这将是可靠的解决方案,而不是使用 SDWebImage。

SwiftyGif

// You can also set it with an URL pointing to your gif
let url = URL(string: "...")
let loader = UIActivityIndicatorView(style: .white)
cell.gifImageView.setGifFromURL(url, customLoader: loader)

【讨论】:

    【解决方案2】:
    • 下载GIF文件,下次获取文件并显示

      Alamofire.download(gifUrl, to: destination).responseJSON(completionHandler: {
          response in
      
          if let filePath = response.destinationURL?.path{
              if let gifImage = UIImage.init(contentsOfFile: filePath){
                  self.imageVIew.image = gifImage
              }
          }
      })
      

    【讨论】:

      猜你喜欢
      • 2018-02-26
      • 2014-07-23
      • 2011-02-01
      • 1970-01-01
      • 2013-05-20
      • 1970-01-01
      • 2018-07-09
      • 2017-04-17
      • 2017-10-10
      相关资源
      最近更新 更多