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() { super.viewDidLoad() performBackgroundOperation() } ... 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:
- The viewDidLoad loads data asynchronously by callingĀ performBackgroundOperation().
- The performBackgroundOperation adds an operation to the OperationQueue calling OperationQueue().addOperation {…}
- 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 {…}.
- After that the self.loadDataAsync() is executed asynchronously within the OperationQueue worker thread.
- When this asynchronous code is finished, the function didLoadData() is executed on the main thread.