Time Consuming Task in Background Thread in Swift

In this short Swift code example, you will learn how to perform a time consuming task in background thread in Swift, to keep mobile app responsive to user actions while the task is being executed and how to update UI from an async task once background task has completed.

  • Do some task in background thread
  • Keep mobile app responsive to user actions while the background task is being executed
  • Update user interface from async task once the background task is completed
  DispatchQueue.global(qos: .userInitiated).async {
    // Do some time consuming task in this background thread
    // Mobile app will remain to be responsive to user actions
    
    print("Performing time consuming task in this background thread")
    
   DispatchQueue.main.async {
        // Task consuming task has completed
        // Update UI from this block of code
        print("Time consuming task has completed. From here we are allowed to update user interface.")
    }
}

For more Swift code examples and tutorials, please check the Swift Code Examples page on this website.


Leave a Reply

Your email address will not be published. Required fields are marked *

Free Video Lessons

Enter your email and stay on top of things,

Subscribe!