Matt
Matt

Reputation: 793

Using threads to update UI with Swift

I'm developing a software with Xcode 6 using Swift. When I press a button, my code takes some informations from the web and writes them on my NSWindow.

So imagine something like this:

@IBAction func buttonPressed(sender: AnyObject)
{
    for page in listOfPages                     //Number of pages is 40.
    {
        var label: NSTextField = NSTextField();

        label.stringValue = getInformetionsFromPage(page)

        /*
             some code to add label in the window here 
        */ 
    }
}

The problem is that once I click the button, it takes a while before I see the list of results, in the main time the app is frozen. That's because I'm not using any threads to handle this problem. How could I implement threads to see every label updated every step of the loop? I'm new with threads and Swift, so I would need some help!

Thank you guys.

Upvotes: 25

Views: 36311

Answers (2)

Fangming
Fangming

Reputation: 25280

Swift 3.0 + version

DispatchQueue.main.async() {
    // your UI update code
}

Posted this because XCode cannot suggest the correct syntax from swift 2.0 version

Upvotes: 57

mustafa
mustafa

Reputation: 15464

There is GCD. Here is a basic usage:

for page in listOfPages {
    var label = NSTextField()
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
        let result = getInformationFromPage(page)
        dispatch_async(dispatch_get_main_queue()) {
            label.stringValue = result
        }
    }
}

dispatch_async function asynchronously runs the block of code on the given queue. In first dispatch_async call we dispatch the code to run on background queue. After we get result we update label on main queue with that result

Upvotes: 14

Related Questions