swift
background-threading
concurrency
iOS-development
swift-programming

How to use background thread in swift?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

In iOS development, it's crucial to maintain a responsive user interface (UI). Long-running tasks or operations can block the main thread, causing the UI to freeze and degrade the user experience. Background threads, or concurrent operations, are often used to keep the main thread free for UI updates. This article details how to use background threads in Swift using Grand Central Dispatch (GCD) and Swift’s OperationQueue.

Understanding Concurrency

Concurrency in iOS is the concept of multiple tasks running simultaneously. Swift supports concurrency through several APIs, with GCD and OperationQueue being the most common.

Grand Central Dispatch (GCD)

GCD is a low-level API for managing concurrent tasks. It offers a simple and powerful model for executing work asynchronously and concurrently.

Key Concepts:

  • Queue: A pool where tasks are submitted. Queues can be serial or concurrent.
  • Serial Queue: Tasks are executed one at a time in the order they are added.
  • Concurrent Queue: Tasks are executed simultaneously, starting as soon as threads are available.
  • Main Queue: A globally available serial queue that runs on the main thread.
  • Global Queue: A globally available concurrent queue.

Using Background Threads with GCD

Creating and Using Queues

Background Queue

To perform an operation in the background, you can use one of GCD’s global concurrent queues:

swift
1DispatchQueue.global(qos: .background).async {
2    // Perform heavy tasks
3    let result = performComplexCalculation()
4    DispatchQueue.main.async {
5        // Update UI with result
6        updateUI(with: result)
7    }
8}

In this example:

  • DispatchQueue.global(qos: .background) retrieves a concurrent background queue.
  • .async executes the task in the background.
  • DispatchQueue.main.async updates the UI on the main thread.

Main Queue

The main queue is where UI updates should happen:

swift
DispatchQueue.main.async {
    // UI updates
}

Quality of Service (QoS) Classes

QoS classes determine the priority of the queue. Options include:

  • .userInteractive: High priority, for UI updates.
  • .userInitiated: Tasks initiated by the user, requiring immediate results.
  • .background: For non-urgent tasks that don't impact the user experience.

Example:

swift
DispatchQueue.global(qos: .userInitiated).async {
    // Task that should complete quickly
}

Using OperationQueue

OperationQueue is a higher-level abstraction compared to GCD. It allows you to manage the lifecycle of operations, dependencies, and cancellations.

Creating an OperationQueue

swift
1let queue = OperationQueue()
2queue.maxConcurrentOperationCount = 2  // Number of concurrent operations
3
4queue.addOperation {
5    // Background Task
6    let data = fetchDataFromServer()
7    OperationQueue.main.addOperation {
8        // Update UI
9        updateUI(with: data)
10    }
11}

Operation Subclass

Create custom operations by subclassing Operation:

swift
1class MyOperation: Operation {
2    override func main() {
3        if isCancelled { return }
4        // Perform the task
5    }
6}

Example with Dependency

swift
1let operation1 = MyOperation()
2let operation2 = MyOperation()
3operation2.addDependency(operation1)
4queue.addOperations([operation1, operation2], waitUntilFinished: false)

Best Practices

  1. Do not block the main thread: Always delegate heavy tasks to a background queue.
  2. Use QoS wisely: Select appropriate QoS for tasks to optimize performance.
  3. Limit concurrent operations: Be mindful of the number of concurrent tasks to avoid overwhelming the app.
  4. Keep UI updates on the main thread: Always ensure UI work is performed on the main queue.

Summary Table

ConceptDescription
Serial QueueExecutes tasks one at a time in the order they were added.
Concurrent QueueExecutes tasks concurrently, starting as soon as threads are available.
Main QueueSerial queue that schedules tasks on the main thread, used for UI updates.
Global QueueConcurrent queues with varying QoS levels.
QoS ClassesPriorities for queues, including .userInteractive, .userInitiated, .utility, .background.
OperationQueueHigh-level abstraction managing operations with built-in dependencies, priorities, and cancellation.

By leveraging GCD and OperationQueue, developers can effectively manage background tasks and maintain a fluid user experience in their Swift applications.


Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.