Search code examples
swiftmacosibaction

View/Window won't update until @IBAction is complete


I have a button linked to an IBAction that takes around 5-10 seconds to complete. While the IBAction function is running I want to print progress messages in my view/window. The only message that prints is the last one, and it prints after the IBAction has completed (ie the button is not blue). When I step through the function in the debugger, no messages are visible until I'm out of the function (ie button is not blue).

Any idea on how to update the window while the callback is being executed?


Solution

  • embed the IBAction logic inside a background queue:

    DispatchQueue.global(qos: .background).async {
       // background code
    }
    

    and anytime you need to print the progress in your view/window embed that part inside:

    DispatchQueue.main.async {
       // user interface code
    }    
    

    generally you may want to try this:

    DispatchQueue.global(qos: .background).async {
       //background code
    
       DispatchQueue.main.async {
         //your main thread
       }    
    }