Search code examples
swiftimagegifdispatch

Swift 2 - Prevent stuck of loading big gif file


I have GIF File which is 2MB but when I use celluar and my high speed is over I have 15kb/s and I have to wait certain amount of time to continue using the app..

    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 doesn't work...

How to continue using the app while the image is loading ?


Solution

  • Get off the main thread to perform the download and then get on the main thread to talk to the interface:

    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{}
        })
    }
    

    However, it would be better, as you've been told, to do a proper download with NSURLSession.