Mc.Lover Mc.Lover - 4 months ago 15
Swift Question

App freezes while download a file from server

I am trying to download a txt file from server but app freezes a little bit while I am downloading the string :

override func viewDidAppear(animated: Bool) {



let getPrice = try! String(contentsOfURL: NSURL(string: "http://site.cin/price.txt")!, encoding: NSUTF8StringEncoding)
self.price.text = getPrice


}


I don't want to use AFNetwroking and etc ...

Answer

Try this:

let bgQueue = NSOperationQueue()

        bgQueue.addOperationWithBlock { 
            let getPrice = try! String(contentsOfURL: NSURL(string: "http://site.cin/price.txt")!, encoding: NSUTF8StringEncoding)
            self.price.text = getPrice
        }

This codes runs in background and will not block your main thread so that app will not freeze.

Comments