在uiimageview中加载Gif需要很长时间

时间:2015-04-14 02:19:28

标签: ios swift uiimageview gif

我可以非常轻松地将图像异步加载到我的UITableView中,但是当我尝试加载gif时,我遇到了一大堆问题。

1)如果我向下滚动桌子并向后移动,gif会消失并需要5秒才能回来。普通图像不会发生这种情况 2)gif不会动画。这只是gif的第一帧。

我正在使用此库来加载gif:

import UIKit
import Foundation

class ImageLoader {

var cache = NSCache()

class var sharedLoader : ImageLoader {
  struct Static {
    static let instance : ImageLoader = ImageLoader()
    }
    return Static.instance
}

func imageForUrl(urlString: String, completionHandler:(image: UIImage?, url: String) -> ()) {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), {()in
        var data: NSData? = self.cache.objectForKey(urlString) as? NSData

        if let goodData = data {
            var image = UIImage(data: goodData)

            if (urlString.lowercaseString.rangeOfString("gif") != nil) {
                image = UIImage.animatedImageWithData(goodData)
                println("gif")

            }

            dispatch_async(dispatch_get_main_queue(), {() in
                completionHandler(image: image, url: urlString)
            })
            return
        }

        var downloadTask: NSURLSessionDataTask = NSURLSession.sharedSession().dataTaskWithURL(NSURL(string: urlString)!, completionHandler: {(data: NSData!, response: NSURLResponse!, error: NSError!) -> Void in
            if (error != nil) {
                completionHandler(image: nil, url: urlString)
                return
            }

            if data != nil {
                var image = UIImage(data: data)
                if (urlString.lowercaseString.rangeOfString("gif") != nil) {
                    image = UIImage.animatedImageWithData(data)
                                        println("gif2")

                }

                self.cache.setObject(data, forKey: urlString)
                dispatch_async(dispatch_get_main_queue(), {() in
                    completionHandler(image: image, url: urlString)
                })
                return
            }

        })
        downloadTask.resume()
    })

  }
}

然后我试图在cellforrowatindexpath中显示图像:

 ImageLoader.sharedLoader.imageForUrl(arrayByVotes[indexPath.row].objectForKey("thumbnail") as NSString, completionHandler:{(image: UIImage?, url: String) in

     cell.thumbnail.image = image
     cell.thumbnail.contentMode = UIViewContentMode.Redraw

})

1 个答案:

答案 0 :(得分:0)

UIImageView并不支持动画GIF。要在您的应用中显示动画GIF,您需要使用FLAnimatedImageOLImageView之类的内容。