Swift Update Label (with HTML content) takes 1min
Asked Answered
C

2

8

I got a small problem, let me start with the code

class ViewController: UIViewController {

@IBOutlet weak var LBoutput: UILabel!
@IBAction func BTclick(sender: AnyObject) {
    var url = NSURL(string: "http://google.com")
    println("test0")
    let getdata = NSURLSession.sharedSession().dataTaskWithURL(url){(data ,response , error) in
        var htmlContent = NSString(data: data, encoding: NSUTF8StringEncoding)
        println("test1")
        println("test2")
        self.LBoutput.text = "test6"
    }
    println("test3")
    getdata.resume()
    println("test4")
    LBoutput.text = "test5"

}

This codes give me a output in the console of

test0
test3
test4
test1
test2

Also the label updates to "test5" with no time, but the label to update to "test6" takes like 30sec.

I have no clue why this takes so long, anyone a idea?

Consalve answered 1/9, 2014 at 10:5 Comment(0)
C
32

Usual problem of updating UI in a secondary thread:

Your closure is obviously not running on the main thread, as the URL task is asynchronous. So updating the label on the closure will have to wait for the main thread to run its update loop. The way to fix it is to wrap the .text = call to force it to run on the main thread (which is where the UI stuff should run anyway):

        dispatch_async(dispatch_get_main_queue()) {
            self.LBoutput.text = "test6"
        }
Chlamys answered 1/9, 2014 at 10:35 Comment(2)
I'm not sure why this sample is only printing test3 and test4 and ends with the label showing test5 for me with xcode 6.1.1. I copied the code into a new single view swift project and connected a label and button. My Deployment Target is os ios 8.1. Xcode wouldn't let it run until I changed "dataTaskWithURL(url)" to "dataTaskWithURL(url!)" (with exclamation point) but that's the only change I've made to the sample code. My computer has an internet connection, and I tried running on simulator and iphone. The label still says "test5" after 5 minutes. Am I missing something obvious? Thanks.Kev
What's in the error variable? Your url call must be failing.Chlamys
B
0

In Swift 3:

DispatchQueue.main.async
{
    self.LBoutput.text = "test6"
}
Betthezul answered 16/6, 2017 at 2:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.