Swift 2 - 防止加载大 gif 文件卡住

Swift 2 - Prevent stuck of loading big gif file

我有 2MB 的 GIF 文件,但是当我使用 celluar 并且我的高速结束时,我有 15kb/s,我必须等待一定的时间才能继续使用该应用程序..

    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        getGif()

}

func getGif(){
    dispatch_async(dispatch_get_main_queue(), {
        do{
            if let json = try NSJSONSerialization.JSONObjectWithData(NSData(contentsOfURL: NSURL(string: "http://google.bg/gif.php")!)!, options: .MutableContainers) as? NSArray{
                self.gifUrl = json[0]["url"] as! String
                self.theGif.image = UIImage.gifWithURL(self.gifUrl)
            }
        }catch{}
    })
}

调度不工作...

如何在加载图片时继续使用该应用程序?

您正在主队列上使用 dispatch_async,以便代码在主线程上执行。

试试 dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0))

还有一些很好的库隐藏了 GCD 的复杂性,比如 Async. And if you need more info on GCD itself feel free to look at the Apple Doc

获取off主线程执行下载然后获取on主线程与接口对话:

func getGif(){
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)), {
        do{
            if let json = try NSJSONSerialization.JSONObjectWithData(NSData(contentsOfURL: NSURL(string: "http://google.bg/gif.php")!)!, options: .MutableContainers) as? NSArray{
                dispatch_async(dispatch_get_main_queue(), {
                    self.gifUrl = json[0]["url"] as! String
                    self.theGif.image = UIImage.gifWithURL(self.gifUrl)
                }
            }
        }catch{}
    })
}

但是,如您所知,使用 NSURLSession 进行正确下载会更好。

extension UIImage {
    public class func gifWithURL(gifUrl:String, completion: (data: NSData)->()) {
        let session = NSURLSession.sharedSession()
        let task = session.dataTaskWithURL(NSURL(string: gifUrl)!) { (data, response, error) in
            if error == nil {
                dispatch_async(dispatch_get_main_queue(), {
                completion(data: data!)
                })
            }
        }
        task.resume()
    }
}