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 ?

Answers


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.


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

You are using dispatch_async on the main queue so that code is executed on the main thread.

Try dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) instead.

Also there are some nice libraries that hides GCD complexity like Async. And if you need more info on GCD itself feel free to look at the Apple Doc


Need Your Help

how to access my database which is in pc from other pcs in a local network by using visual studio & C# windows application?

visual-studio-2005

I make a software using C# & my database is msaccess..Now I want to make a gateway which will be install in all pcs in a local network & i want to make connection with that database which i...

javascript cross-domain issue

javascript cross-domain

I am building a small widget that I am giving to users to embed in their websites and blogs. Now the widget loads a javascript file in the page where it is embedded from my server, which in turn pu...