iOS Swift 4 Coding

How to run code in the background using Swift?

7 views August 31, 2018 August 31, 2018 bicobro 0

To run code in the background you can use the iOS OperationQueue. You can simply add an operation to the queue and the iOS platform will take responsibility for handling it on time.

Main thread UI access

You have to understand that an operation within the queue is NOT performed on the main thread. This means that, if you want to change UI stuff, you need to go back to the main thread to perform changes. This can be done by calling OperationQueue.main.addOperation.

override func viewDidLoad() {


private func performBackgroundOperation() {
    // Add async operation
    OperationQueue().addOperation {
        OperationQueue.main.addOperation { 
            self.willLoadData() // on main thread
        self.loadDataAsync() // async
        OperationQueue.main.addOperation { 
            self.didLoadData() // on main thread

func loadDataAsync() {
    // do something on the main thread before loading

func willLoadData() {
    // do something async

func didLoadData() {
    // do something on the main thread after loading

In the example above, a UIViewController is decorated with asynchronous load function, the following happens:

  1. The viewDidLoad loads data asynchronously by callingĀ performBackgroundOperation().
  2. The performBackgroundOperation adds an operation to the OperationQueue calling OperationQueue().addOperation {…}
  3. The code now runs the WillLoadData() function on the main thread where UI actions can be performed. This is enforced by the call OperationQueue.main.addOperation {…}.
  4. After that the self.loadDataAsync() is executed asynchronously within the OperationQueue worker thread.
  5. When this asynchronous code is finished, the function didLoadData() is executed on the main thread.

Was this helpful?