blog.stackademic.com 15 min read Original Source

Background Tasks in iOS: The Complete Guide

Background tasks are tricky. Here’s how they really work.

You need to download files in the background. You need to sync data. You need to process tasks. You try background tasks. They don’t work. They get killed. You’re confused.

Here’s the thing: Background tasks in iOS are complex. There are multiple APIs. Each has different rules. Each has different limitations. Use the wrong one, and your task gets killed. Use the right one, and it works perfectly.

This guide will show you:

  • All background task APIs in iOS
  • When to use each API
  • How to implement each correctly
  • Common pitfalls and how to avoid them
  • Real-world patterns that work

By the end, you’ll understand background tasks deeply. You’ll choose the right API. You’ll implement it correctly. Your tasks will run reliably.

Let’s master background tasks.

Understanding Background Execution

iOS limits background execution to save battery. Understanding these limits is crucial.

Background Execution Limits

Foreground: App is active, unlimited execution time Background (recently backgrounded): ~30 seconds to finish work Background (suspended): App is suspended, no execution Terminated: App is killed, no execution

Background Execution Options

beginBackgroundTask: Short tasks when app goes to background BGTaskScheduler: Scheduled background work URLSession Background: Background downloads/uploads Background Modes: Special capabilities (audio, location, etc.)

beginBackgroundTask: Quick Background Work

beginBackgroundTask gives you ~30 seconds to finish work when the app goes to background.

When to Use

Use for quick cleanup tasks: Save data, cancel network requests, invalidate timers

Basic Implementation

func applicationDidEnterBackground(_ application: UIApplication) {
    var backgroundTaskID: UIBackgroundTaskIdentifier = .invalid

    backgroundTaskID = application.beginBackgroundTask {
        // Called when time expires
        application.endBackgroundTask(backgroundTaskID)
        backgroundTaskID = .invalid
    }

    // Do your work
    saveCriticalData { [weak self] in
        application.endBackgroundTask(backgroundTaskID)
        backgroundTaskID = .invalid
    }
}
func applicationDidEnterBackground(_ application: UIApplication) {
    var backgroundTaskID: UIBackgroundTaskIdentifier = .invalid

    backgroundTaskID = application.beginBackgroundTask {
        // Called when time expires
        application.endBackgroundTask(backgroundTaskID)
        backgroundTaskID = .invalid
    }

    // Do your work
    saveCriticalData { [weak self] in
        application.endBackgroundTask(backgroundTaskID)
        backgroundTaskID = .invalid
    }
}

Common Mistakes

Mistake 1: Not Ending the Task

// ❌ Bad: Never ends the task
let taskID = application.beginBackgroundTask {
    // Expiration handler
}
// Task never ends, app gets killed
// ❌ Bad: Never ends the task
let taskID = application.beginBackgroundTask {
    // Expiration handler
}
// Task never ends, app gets killed

Mistake 2: Ending Too Early

// ❌ Bad: Ends before work completes
let taskID = application.beginBackgroundTask { }
saveData() // Async work
application.endBackgroundTask(taskID) // Ends too early!
// ❌ Bad: Ends before work completes
let taskID = application.beginBackgroundTask { }
saveData() // Async work
application.endBackgroundTask(taskID) // Ends too early!

Mistake 3: Not Handling Expiration

// ❌ Bad: No expiration handler
let taskID = application.beginBackgroundTask(expirationHandler: nil)
// App gets killed if time expires
// ❌ Bad: No expiration handler
let taskID = application.beginBackgroundTask(expirationHandler: nil)
// App gets killed if time expires

Correct Pattern

Void) {
startBackgroundTask()

// Do your work
performWork { [weak self] in
completion()
self?.endBackgroundTask()
}
}
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

class BackgroundTaskManager {
    private var backgroundTaskID: UIBackgroundTaskIdentifier = .invalid

    func startBackgroundTask() {
        guard backgroundTaskID == .invalid else { return }

        backgroundTaskID = UIApplication.shared.beginBackgroundTask { [weak self] in
            self?.endBackgroundTask()
        }
    }

    func endBackgroundTask() {
        guard backgroundTaskID != .invalid else { return }
        UIApplication.shared.endBackgroundTask(backgroundTaskID)
        backgroundTaskID = .invalid
    }

    func performBackgroundWork(completion: @escaping () -> Void) {
        startBackgroundTask()

        // Do your work
        performWork { [weak self] in
            completion()
            self?.endBackgroundTask()
        }
    }
}
class BackgroundTaskManager {
    private var backgroundTaskID: UIBackgroundTaskIdentifier = .invalid

    func startBackgroundTask() {
        guard backgroundTaskID == .invalid else { return }

        backgroundTaskID = UIApplication.shared.beginBackgroundTask { [weak self] in
            self?.endBackgroundTask()
        }
    }

    func endBackgroundTask() {
        guard backgroundTaskID != .invalid else { return }
        UIApplication.shared.endBackgroundTask(backgroundTaskID)
        backgroundTaskID = .invalid
    }

    func performBackgroundWork(completion: @escaping () -> Void) {
        startBackgroundTask()

        // Do your work
        performWork { [weak self] in
            completion()
            self?.endBackgroundTask()
        }
    }
}

BGTaskScheduler: Scheduled Background Work

BGTaskScheduler schedules background work to run at optimal times. iOS decides when to run it.

When to Use

Use for scheduled work: Background fetch, data processing, content updates

Registering Tasks

First, register your task identifiers in Info.plist:

<button data-code="BGTaskSchedulerPermittedIdentifiers

com.yourapp.background-fetch
com.yourapp.data-processing
” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

<key>BGTaskSchedulerPermittedIdentifiers</key>
<array>
    <string>com.yourapp.background-fetch</string>
    <string>com.yourapp.data-processing</string>
</array>
<key>BGTaskSchedulerPermittedIdentifiers</key>
<array>
    <string>com.yourapp.background-fetch</string>
    <string>com.yourapp.data-processing</string>
</array>

Background Fetch

Background fetch updates your app’s content in the background.

Step 1: Register in App Delegate

Bool {
BGTaskScheduler.shared.register(forTaskWithIdentifier: "com.yourapp.background-fetch", using: nil) { task in
self.handleBackgroundFetch(task: task as! BGAppRefreshTask)
}
return true
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    BGTaskScheduler.shared.register(forTaskWithIdentifier: "com.yourapp.background-fetch", using: nil) { task in
        self.handleBackgroundFetch(task: task as! BGAppRefreshTask)
    }
    return true
}
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    BGTaskScheduler.shared.register(forTaskWithIdentifier: "com.yourapp.background-fetch", using: nil) { task in
        self.handleBackgroundFetch(task: task as! BGAppRefreshTask)
    }
    return true
}

Step 2: Schedule the Task

func scheduleBackgroundFetch() {
    let request = BGAppRefreshTaskRequest(identifier: "com.yourapp.background-fetch")
    request.earliestBeginDate = Date(timeIntervalSinceNow: 15 * 60) // 15 minutes from now

    do {
        try BGTaskScheduler.shared.submit(request)
    } catch {
        print("Could not schedule background fetch: (error)")
    }
}
func scheduleBackgroundFetch() {
    let request = BGAppRefreshTaskRequest(identifier: "com.yourapp.background-fetch")
    request.earliestBeginDate = Date(timeIntervalSinceNow: 15 * 60) // 15 minutes from now

    do {
        try BGTaskScheduler.shared.submit(request)
    } catch {
        print("Could not schedule background fetch: (error)")
    }
}

Step 3: Handle the Task

func handleBackgroundFetch(task: BGAppRefreshTask) {
    // Schedule next fetch
    scheduleBackgroundFetch()

    // Set expiration handler
    task.expirationHandler = {
        task.setTaskCompleted(success: false)
    }

    // Perform fetch
    fetchNewContent { hasNewContent in
        task.setTaskCompleted(success: hasNewContent)
    }
}
func handleBackgroundFetch(task: BGAppRefreshTask) {
    // Schedule next fetch
    scheduleBackgroundFetch()

    // Set expiration handler
    task.expirationHandler = {
        task.setTaskCompleted(success: false)
    }

    // Perform fetch
    fetchNewContent { hasNewContent in
        task.setTaskCompleted(success: hasNewContent)
    }
}

Background Processing

Background processing runs longer tasks in the background.

Step 1: Register

Bool {
BGTaskScheduler.shared.register(forTaskWithIdentifier: "com.yourapp.data-processing", using: nil) { task in
self.handleBackgroundProcessing(task: task as! BGProcessingTask)
}
return true
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    BGTaskScheduler.shared.register(forTaskWithIdentifier: "com.yourapp.data-processing", using: nil) { task in
        self.handleBackgroundProcessing(task: task as! BGProcessingTask)
    }
    return true
}
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    BGTaskScheduler.shared.register(forTaskWithIdentifier: "com.yourapp.data-processing", using: nil) { task in
        self.handleBackgroundProcessing(task: task as! BGProcessingTask)
    }
    return true
}

Step 2: Schedule

func scheduleBackgroundProcessing() {
    let request = BGProcessingTaskRequest(identifier: "com.yourapp.data-processing")
    request.requiresNetworkConnectivity = true
    request.requiresExternalPower = false
    request.earliestBeginDate = Date(timeIntervalSinceNow: 1 * 60 * 60) // 1 hour from now

    do {
        try BGTaskScheduler.shared.submit(request)
    } catch {
        print("Could not schedule background processing: (error)")
    }
}
func scheduleBackgroundProcessing() {
    let request = BGProcessingTaskRequest(identifier: "com.yourapp.data-processing")
    request.requiresNetworkConnectivity = true
    request.requiresExternalPower = false
    request.earliestBeginDate = Date(timeIntervalSinceNow: 1 * 60 * 60) // 1 hour from now

    do {
        try BGTaskScheduler.shared.submit(request)
    } catch {
        print("Could not schedule background processing: (error)")
    }
}

Step 3: Handle

func handleBackgroundProcessing(task: BGProcessingTask) {
    task.expirationHandler = {
        task.setTaskCompleted(success: false)
    }

    processData { success in
        task.setTaskCompleted(success: success)
    }
}
func handleBackgroundProcessing(task: BGProcessingTask) {
    task.expirationHandler = {
        task.setTaskCompleted(success: false)
    }

    processData { success in
        task.setTaskCompleted(success: success)
    }
}

Task Requirements

BGAppRefreshTask:

  • Quick tasks (< 30 seconds)
  • Content updates
  • Requires network (optional)

BGProcessingTask:

  • Longer tasks (minutes)
  • Data processing
  • Can require network, external power

URLSession Background Downloads

URLSession can download files in the background, even when the app is terminated.

When to Use

Use for file downloads: Large files, media files, content downloads

Configuration

let config = URLSessionConfiguration.background(withIdentifier: "com.yourapp.downloads")
config.isDiscretionary = false // Run even on cellular
config.sessionSendsLaunchEvents = true // Launch app when complete

let session = URLSession(configuration: config, delegate: self, delegateQueue: nil)
let config = URLSessionConfiguration.background(withIdentifier: "com.yourapp.downloads")
config.isDiscretionary = false // Run even on cellular
config.sessionSendsLaunchEvents = true // Launch app when complete

let session = URLSession(configuration: config, delegate: self, delegateQueue: nil)

Implementation

Step 1: Create Download Task

func downloadFile(url: URL) {
    let task = urlSession.downloadTask(with: url)
    task.resume()
}
func downloadFile(url: URL) {
    let task = urlSession.downloadTask(with: url)
    task.resume()
}

Step 2: Handle Completion

func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
    // Move file from temporary location
    let documentsPath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
    let destinationURL = documentsPath.appendingPathComponent("downloaded-file")

    try? FileManager.default.moveItem(at: location, to: destinationURL)
}
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
    // Move file from temporary location
    let documentsPath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
    let destinationURL = documentsPath.appendingPathComponent("downloaded-file")

    try? FileManager.default.moveItem(at: location, to: destinationURL)
}

Step 3: Handle Background Completion

Void) {
// Store completion handler
backgroundCompletionHandler = completionHandler

// Recreate session if needed
if urlSession == nil {
let config = URLSessionConfiguration.background(withIdentifier: identifier)
urlSession = URLSession(configuration: config, delegate: self, delegateQueue: nil)
}
}

func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) {
DispatchQueue.main.async {
self.backgroundCompletionHandler?()
self.backgroundCompletionHandler = nil
}
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

func application(_ application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: @escaping () -> Void) {
    // Store completion handler
    backgroundCompletionHandler = completionHandler

    // Recreate session if needed
    if urlSession == nil {
        let config = URLSessionConfiguration.background(withIdentifier: identifier)
        urlSession = URLSession(configuration: config, delegate: self, delegateQueue: nil)
    }
}

func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) {
    DispatchQueue.main.async {
        self.backgroundCompletionHandler?()
        self.backgroundCompletionHandler = nil
    }
}
func application(_ application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: @escaping () -> Void) {
    // Store completion handler
    backgroundCompletionHandler = completionHandler

    // Recreate session if needed
    if urlSession == nil {
        let config = URLSessionConfiguration.background(withIdentifier: identifier)
        urlSession = URLSession(configuration: config, delegate: self, delegateQueue: nil)
    }
}

func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) {
    DispatchQueue.main.async {
        self.backgroundCompletionHandler?()
        self.backgroundCompletionHandler = nil
    }
}

Monitoring Progress

func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
    let progress = Double(totalBytesWritten) / Double(totalBytesExpectedToWrite)
    print("Download progress: (progress * 100)%")
}
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
    let progress = Double(totalBytesWritten) / Double(totalBytesExpectedToWrite)
    print("Download progress: (progress * 100)%")
}

Background Modes

Background modes give your app special background execution capabilities.

Available Background Modes

audio: Audio playback in background location: Location updates in background voip: VoIP calls newsstand-content: Newsstand downloads external-accessory: External accessory communication bluetooth-central: Bluetooth communication bluetooth-peripheral: Bluetooth peripheral mode fetch: Background fetch (deprecated, use BGTaskScheduler) remote-notification: Remote notification processing processing: Background processing (deprecated, use BGTaskScheduler)

Enabling Background Modes

Add to Info.plist:

<button data-code="UIBackgroundModes

audio
fetch
” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

<key>UIBackgroundModes</key>
<array>
    <string>audio</string>
    <string>fetch</string>
</array>
<key>UIBackgroundModes</key>
<array>
    <string>audio</string>
    <string>fetch</string>
</array>

Audio Background Mode

// Configure audio session
let audioSession = AVAudioSession.sharedInstance()
try audioSession.setCategory(.playback, mode: .default)
try audioSession.setActive(true)

// Audio continues playing in background
// Configure audio session
let audioSession = AVAudioSession.sharedInstance()
try audioSession.setCategory(.playback, mode: .default)
try audioSession.setActive(true)

// Audio continues playing in background

Location Background Mode

// Start location updates
locationManager.allowsBackgroundLocationUpdates = true
locationManager.startUpdatingLocation()
// Start location updates
locationManager.allowsBackgroundLocationUpdates = true
locationManager.startUpdatingLocation()

Important: Only enable if you really need it. Users see location indicator.

Real-World Patterns

Pattern 1: Background Data Sync

Sync data in the background using BGTaskScheduler:

class DataSyncManager {
    func setupBackgroundSync() {
        BGTaskScheduler.shared.register(forTaskWithIdentifier: "com.yourapp.sync", using: nil) { task in
            self.handleSync(task: task as! BGAppRefreshTask)
        }
    }

    func scheduleSync() {
        let request = BGAppRefreshTaskRequest(identifier: "com.yourapp.sync")
        request.earliestBeginDate = Date(timeIntervalSinceNow: 15 * 60)

        try? BGTaskScheduler.shared.submit(request)
    }

    func handleSync(task: BGAppRefreshTask) {
        scheduleSync() // Schedule next sync

        task.expirationHandler = {
            task.setTaskCompleted(success: false)
        }

        syncData { success in
            task.setTaskCompleted(success: success)
        }
    }
}
class DataSyncManager {
    func setupBackgroundSync() {
        BGTaskScheduler.shared.register(forTaskWithIdentifier: "com.yourapp.sync", using: nil) { task in
            self.handleSync(task: task as! BGAppRefreshTask)
        }
    }

    func scheduleSync() {
        let request = BGAppRefreshTaskRequest(identifier: "com.yourapp.sync")
        request.earliestBeginDate = Date(timeIntervalSinceNow: 15 * 60)

        try? BGTaskScheduler.shared.submit(request)
    }

    func handleSync(task: BGAppRefreshTask) {
        scheduleSync() // Schedule next sync

        task.expirationHandler = {
            task.setTaskCompleted(success: false)
        }

        syncData { success in
            task.setTaskCompleted(success: success)
        }
    }
}

Pattern 2: Background File Download

Download files in background using URLSession:

Void)?

override init() {
super.init()
let config = URLSessionConfiguration.background(withIdentifier: "com.yourapp.downloads")
urlSession = URLSession(configuration: config, delegate: self, delegateQueue: nil)
}

func download(url: URL) {
let task = urlSession.downloadTask(with: url)
task.resume()
}

func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
// Handle downloaded file
}

func application(_ application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: @escaping () -> Void) {
backgroundCompletionHandler = completionHandler
}

func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) {
DispatchQueue.main.async {
self.backgroundCompletionHandler?()
self.backgroundCompletionHandler = nil
}
}
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

class DownloadManager: NSObject, URLSessionDownloadDelegate {
    private var urlSession: URLSession!
    private var backgroundCompletionHandler: (() -> Void)?

    override init() {
        super.init()
        let config = URLSessionConfiguration.background(withIdentifier: "com.yourapp.downloads")
        urlSession = URLSession(configuration: config, delegate: self, delegateQueue: nil)
    }

    func download(url: URL) {
        let task = urlSession.downloadTask(with: url)
        task.resume()
    }

    func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
        // Handle downloaded file
    }

    func application(_ application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: @escaping () -> Void) {
        backgroundCompletionHandler = completionHandler
    }

    func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) {
        DispatchQueue.main.async {
            self.backgroundCompletionHandler?()
            self.backgroundCompletionHandler = nil
        }
    }
}
class DownloadManager: NSObject, URLSessionDownloadDelegate {
    private var urlSession: URLSession!
    private var backgroundCompletionHandler: (() -> Void)?

    override init() {
        super.init()
        let config = URLSessionConfiguration.background(withIdentifier: "com.yourapp.downloads")
        urlSession = URLSession(configuration: config, delegate: self, delegateQueue: nil)
    }

    func download(url: URL) {
        let task = urlSession.downloadTask(with: url)
        task.resume()
    }

    func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
        // Handle downloaded file
    }

    func application(_ application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: @escaping () -> Void) {
        backgroundCompletionHandler = completionHandler
    }

    func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) {
        DispatchQueue.main.async {
            self.backgroundCompletionHandler?()
            self.backgroundCompletionHandler = nil
        }
    }
}

Pattern 3: Quick Background Save

Save data quickly when app goes to background:

class DataManager {
    private var backgroundTaskID: UIBackgroundTaskIdentifier = .invalid

    func saveDataWhenBackgrounded() {
        guard backgroundTaskID == .invalid else { return }

        backgroundTaskID = UIApplication.shared.beginBackgroundTask {
            UIApplication.shared.endBackgroundTask(self.backgroundTaskID)
            self.backgroundTaskID = .invalid
        }

        saveData { [weak self] in
            guard let self = self else { return }
            UIApplication.shared.endBackgroundTask(self.backgroundTaskID)
            self.backgroundTaskID = .invalid
        }
    }
}
class DataManager {
    private var backgroundTaskID: UIBackgroundTaskIdentifier = .invalid

    func saveDataWhenBackgrounded() {
        guard backgroundTaskID == .invalid else { return }

        backgroundTaskID = UIApplication.shared.beginBackgroundTask {
            UIApplication.shared.endBackgroundTask(self.backgroundTaskID)
            self.backgroundTaskID = .invalid
        }

        saveData { [weak self] in
            guard let self = self else { return }
            UIApplication.shared.endBackgroundTask(self.backgroundTaskID)
            self.backgroundTaskID = .invalid
        }
    }
}

Common Pitfalls

Pitfall 1: Not Scheduling Next Task

BGTaskScheduler tasks run once. You must schedule the next one.

// ❌ Bad: Doesn't schedule next task
func handleBackgroundFetch(task: BGAppRefreshTask) {
    fetchData { _ in
        task.setTaskCompleted(success: true)
    }
    // No next task scheduled!
}

// ✅ Good: Schedules next task
func handleBackgroundFetch(task: BGAppRefreshTask) {
    scheduleBackgroundFetch() // Schedule next

    fetchData { _ in
        task.setTaskCompleted(success: true)
    }
}
// ❌ Bad: Doesn't schedule next task
func handleBackgroundFetch(task: BGAppRefreshTask) {
    fetchData { _ in
        task.setTaskCompleted(success: true)
    }
    // No next task scheduled!
}

// ✅ Good: Schedules next task
func handleBackgroundFetch(task: BGAppRefreshTask) {
    scheduleBackgroundFetch() // Schedule next

    fetchData { _ in
        task.setTaskCompleted(success: true)
    }
}

Pitfall 2: Not Handling Expiration

Tasks can expire. Handle expiration properly.

// ❌ Bad: No expiration handler
func handleBackgroundFetch(task: BGAppRefreshTask) {
    fetchData { _ in
        task.setTaskCompleted(success: true)
    }
}

// ✅ Good: Handles expiration
func handleBackgroundFetch(task: BGAppRefreshTask) {
    task.expirationHandler = {
        task.setTaskCompleted(success: false)
    }

    fetchData { _ in
        task.setTaskCompleted(success: true)
    }
}
// ❌ Bad: No expiration handler
func handleBackgroundFetch(task: BGAppRefreshTask) {
    fetchData { _ in
        task.setTaskCompleted(success: true)
    }
}

// ✅ Good: Handles expiration
func handleBackgroundFetch(task: BGAppRefreshTask) {
    task.expirationHandler = {
        task.setTaskCompleted(success: false)
    }

    fetchData { _ in
        task.setTaskCompleted(success: true)
    }
}

Pitfall 3: Not Calling setTaskCompleted

Always call setTaskCompleted, even on failure.

// ❌ Bad: Doesn't call setTaskCompleted on error
func handleBackgroundFetch(task: BGAppRefreshTask) {
    fetchData { success in
        if success {
            task.setTaskCompleted(success: true)
        }
        // Doesn't call on failure!
    }
}

// ✅ Good: Always calls setTaskCompleted
func handleBackgroundFetch(task: BGAppRefreshTask) {
    fetchData { success in
        task.setTaskCompleted(success: success)
    }
}
// ❌ Bad: Doesn't call setTaskCompleted on error
func handleBackgroundFetch(task: BGAppRefreshTask) {
    fetchData { success in
        if success {
            task.setTaskCompleted(success: true)
        }
        // Doesn't call on failure!
    }
}

// ✅ Good: Always calls setTaskCompleted
func handleBackgroundFetch(task: BGAppRefreshTask) {
    fetchData { success in
        task.setTaskCompleted(success: success)
    }
}

Pitfall 4: Not Recreating URLSession

URLSession must be recreated in handleEventsForBackgroundURLSession.

Void) {
backgroundCompletionHandler = completionHandler
// Session might be nil!
}

// ✅ Good: Recreates session
func application(_ application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: @escaping () -> Void) {
backgroundCompletionHandler = completionHandler

if urlSession == nil {
let config = URLSessionConfiguration.background(withIdentifier: identifier)
urlSession = URLSession(configuration: config, delegate: self, delegateQueue: nil)
}
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

// ❌ Bad: Doesn't recreate session
func application(_ application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: @escaping () -> Void) {
    backgroundCompletionHandler = completionHandler
    // Session might be nil!
}

// ✅ Good: Recreates session
func application(_ application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: @escaping () -> Void) {
    backgroundCompletionHandler = completionHandler

    if urlSession == nil {
        let config = URLSessionConfiguration.background(withIdentifier: identifier)
        urlSession = URLSession(configuration: config, delegate: self, delegateQueue: nil)
    }
}
// ❌ Bad: Doesn't recreate session
func application(_ application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: @escaping () -> Void) {
    backgroundCompletionHandler = completionHandler
    // Session might be nil!
}

// ✅ Good: Recreates session
func application(_ application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: @escaping () -> Void) {
    backgroundCompletionHandler = completionHandler

    if urlSession == nil {
        let config = URLSessionConfiguration.background(withIdentifier: identifier)
        urlSession = URLSession(configuration: config, delegate: self, delegateQueue: nil)
    }
}

Best Practices

Practice 1: Choose the Right API

Use the right API for your use case: beginBackgroundTask for quick work, BGTaskScheduler for scheduled work, URLSession for downloads

Practice 2: Always Schedule Next Task

BGTaskScheduler tasks run once. Always schedule the next task.

Practice 3: Handle Expiration

Tasks can expire. Always set expiration handlers.

Practice 4: Call Completion Handlers

Always call completion handlers: setTaskCompleted for BGTaskScheduler, endBackgroundTask for beginBackgroundTask

Practice 5: Test on Real Devices

Background tasks behave differently on real devices. Test on real devices.

Testing Background Tasks

Test 1: beginBackgroundTask

Test quick background work:

  1. Run app on device
  2. Trigger background task
  3. Background the app
  4. Verify task completes
  5. Check it doesn’t exceed 30 seconds

Test 2: BGTaskScheduler

Test scheduled background work:

  1. Schedule background fetch
  2. Wait for system to run it
  3. Check logs for execution
  4. Verify next task is scheduled
  5. Test expiration handling

Test 3: URLSession Background

Test background downloads:

  1. Start download
  2. Background the app
  3. Wait for download to complete
  4. Verify file is downloaded
  5. Check completion handler is called

Debugging Background Tasks

Enable Background Task Logging

Add logging to track background task execution:

func handleBackgroundFetch(task: BGAppRefreshTask) {
    print("Background fetch started")

    task.expirationHandler = {
        print("Background fetch expired")
        task.setTaskCompleted(success: false)
    }

    fetchData { success in
        print("Background fetch completed: (success)")
        task.setTaskCompleted(success: success)
    }
}
func handleBackgroundFetch(task: BGAppRefreshTask) {
    print("Background fetch started")

    task.expirationHandler = {
        print("Background fetch expired")
        task.setTaskCompleted(success: false)
    }

    fetchData { success in
        print("Background fetch completed: (success)")
        task.setTaskCompleted(success: success)
    }
}

Check Task Status

Check if tasks are scheduled:

BGTaskScheduler.shared.getPendingTaskRequests { requests in
    print("Pending tasks: (requests.count)")
    for request in requests {
        print("Task: (request.identifier), earliest: (request.earliestBeginDate)")
    }
}
BGTaskScheduler.shared.getPendingTaskRequests { requests in
    print("Pending tasks: (requests.count)")
    for request in requests {
        print("Task: (request.identifier), earliest: (request.earliestBeginDate)")
    }
}

Monitor Background Execution

Use Instruments to monitor background execution:

  1. Product → Profile → System Trace
  2. Record your app
  3. Background the app
  4. Check background execution time
  5. Identify issues

Key Takeaways

  1. Choose the right API — beginBackgroundTask for quick work, BGTaskScheduler for scheduled work, URLSession for downloads
  2. Always schedule next task — BGTaskScheduler tasks run once, schedule the next one
  3. Handle expiration — Tasks can expire, always set expiration handlers
  4. Call completion handlers — Always call setTaskCompleted or endBackgroundTask
  5. Test on real devices — Background tasks behave differently on real devices
  6. Use background modes wisely — Only enable what you need
  7. Monitor execution — Use logging and Instruments to debug

The Simple Rule:

  • Quick work? → beginBackgroundTask
  • Scheduled work? → BGTaskScheduler
  • Downloads? → URLSession background
  • Special needs? → Background modes
  • Always → Schedule next, handle expiration, call completion

Advanced Techniques

Technique 1: Chaining Background Tasks

Chain multiple background tasks for complex workflows:

class TaskChainManager {
    func chainBackgroundTasks() {
        let task1 = BGAppRefreshTaskRequest(identifier: "com.yourapp.task1")
        let task2 = BGAppRefreshTaskRequest(identifier: "com.yourapp.task2")

        task1.earliestBeginDate = Date(timeIntervalSinceNow: 5 * 60)
        task2.earliestBeginDate = Date(timeIntervalSinceNow: 10 * 60)

        try? BGTaskScheduler.shared.submit(task1)
        try? BGTaskScheduler.shared.submit(task2)
    }

    func handleTask1(task: BGAppRefreshTask) {
        scheduleTask1() // Schedule next

        task.expirationHandler = {
            task.setTaskCompleted(success: false)
        }

        performTask1 { success in
            if success {
                // Trigger task 2
                self.scheduleTask2()
            }
            task.setTaskCompleted(success: success)
        }
    }
}
class TaskChainManager {
    func chainBackgroundTasks() {
        let task1 = BGAppRefreshTaskRequest(identifier: "com.yourapp.task1")
        let task2 = BGAppRefreshTaskRequest(identifier: "com.yourapp.task2")

        task1.earliestBeginDate = Date(timeIntervalSinceNow: 5 * 60)
        task2.earliestBeginDate = Date(timeIntervalSinceNow: 10 * 60)

        try? BGTaskScheduler.shared.submit(task1)
        try? BGTaskScheduler.shared.submit(task2)
    }

    func handleTask1(task: BGAppRefreshTask) {
        scheduleTask1() // Schedule next

        task.expirationHandler = {
            task.setTaskCompleted(success: false)
        }

        performTask1 { success in
            if success {
                // Trigger task 2
                self.scheduleTask2()
            }
            task.setTaskCompleted(success: success)
        }
    }
}

Technique 2: Conditional Task Scheduling

Schedule tasks conditionally based on app state:

class ConditionalTaskManager {
    func scheduleIfNeeded() {
        // Only schedule if user is logged in
        if UserManager.shared.isLoggedIn {
            scheduleBackgroundFetch()
        }
    }

    func scheduleBackgroundFetch() {
        let request = BGAppRefreshTaskRequest(identifier: "com.yourapp.fetch")
        request.earliestBeginDate = Date(timeIntervalSinceNow: 15 * 60)
        try? BGTaskScheduler.shared.submit(request)
    }
}
class ConditionalTaskManager {
    func scheduleIfNeeded() {
        // Only schedule if user is logged in
        if UserManager.shared.isLoggedIn {
            scheduleBackgroundFetch()
        }
    }

    func scheduleBackgroundFetch() {
        let request = BGAppRefreshTaskRequest(identifier: "com.yourapp.fetch")
        request.earliestBeginDate = Date(timeIntervalSinceNow: 15 * 60)
        try? BGTaskScheduler.shared.submit(request)
    }
}

Technique 3: Task Priority Management

Manage task priorities by canceling and rescheduling:

class PriorityTaskManager {
    func rescheduleWithHigherPriority() {
        // Cancel existing task
        BGTaskScheduler.shared.cancel(taskRequestWithIdentifier: "com.yourapp.fetch")

        // Schedule with earlier date
        let request = BGAppRefreshTaskRequest(identifier: "com.yourapp.fetch")
        request.earliestBeginDate = Date(timeIntervalSinceNow: 5 * 60) // Sooner
        try? BGTaskScheduler.shared.submit(request)
    }
}
class PriorityTaskManager {
    func rescheduleWithHigherPriority() {
        // Cancel existing task
        BGTaskScheduler.shared.cancel(taskRequestWithIdentifier: "com.yourapp.fetch")

        // Schedule with earlier date
        let request = BGAppRefreshTaskRequest(identifier: "com.yourapp.fetch")
        request.earliestBeginDate = Date(timeIntervalSinceNow: 5 * 60) // Sooner
        try? BGTaskScheduler.shared.submit(request)
    }
}

URLSession Background Uploads

URLSession can also upload files in the background.

Configuration

let config = URLSessionConfiguration.background(withIdentifier: "com.yourapp.uploads")
config.isDiscretionary = false
config.sessionSendsLaunchEvents = true

let session = URLSession(configuration: config, delegate: self, delegateQueue: nil)
let config = URLSessionConfiguration.background(withIdentifier: "com.yourapp.uploads")
config.isDiscretionary = false
config.sessionSendsLaunchEvents = true

let session = URLSession(configuration: config, delegate: self, delegateQueue: nil)

Implementation

func uploadFile(url: URL, fileData: Data) {
    var request = URLRequest(url: url)
    request.httpMethod = "POST"

    let task = urlSession.uploadTask(with: request, from: fileData)
    task.resume()
}

func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
    if let error = error {
        print("Upload failed: (error)")
    } else {
        print("Upload completed")
    }
}
func urlSession(_ session: URLSession, task: URLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
    let progress = Double(totalBytesSent) / Double(totalBytesExpectedToSend)
    print("Upload progress: (progress * 100)%")
}
func uploadFile(url: URL, fileData: Data) {
    var request = URLRequest(url: url)
    request.httpMethod = "POST"

    let task = urlSession.uploadTask(with: request, from: fileData)
    task.resume()
}

func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
    if let error = error {
        print("Upload failed: (error)")
    } else {
        print("Upload completed")
    }
}
func urlSession(_ session: URLSession, task: URLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
    let progress = Double(totalBytesSent) / Double(totalBytesExpectedToSend)
    print("Upload progress: (progress * 100)%")
}

Background Task Lifecycle

Understanding the lifecycle helps debug issues.

beginBackgroundTask Lifecycle

  1. App goes to background
  2. beginBackgroundTask called
  3. ~30 seconds to complete work
  4. endBackgroundTask called
  5. If not ended, app terminated

BGTaskScheduler Lifecycle

  1. Task scheduled
  2. iOS decides when to run (based on usage)
  3. Task handler called
  4. Task executes
  5. setTaskCompleted called
  6. Next task scheduled (if needed)

URLSession Background Lifecycle

  1. Download/upload started
  2. App can be backgrounded or terminated
  3. System continues download/upload
  4. App launched when complete
  5. Completion handler called

Performance Considerations

Battery Impact

Background tasks impact battery. Optimize for efficiency:

Minimize Work: Do only essential work in background Batch Operations: Process data in batches Use Efficient APIs: Use appropriate APIs for your use case Monitor Usage: Track background execution time

Network Usage

Background network usage drains battery:

Batch Requests: Combine multiple requests Cache Responses: Cache to avoid repeated requests Compress Data: Compress requests and responses Use Efficient Formats: Use efficient data formats

CPU Usage

Background CPU usage drains battery:

Optimize Algorithms: Use efficient algorithms Cache Computations: Cache expensive computations Batch Processing: Process data in batches Avoid Tight Loops: Avoid CPU-intensive loops

Real-World Case Studies

Case Study 1: News App Background Fetch

Requirement: Update news content in background Solution: BGTaskScheduler with BGAppRefreshTask Implementation: Fetch new articles every 15 minutes Result: Content always fresh, minimal battery impact

Case Study 2: Music App Background Downloads

Requirement: Download music files in background Solution: URLSession background downloads Implementation: Download queue with background support Result: Downloads continue even when app terminated

Case Study 3: Social App Data Sync

Requirement: Sync user data in background Solution: BGTaskScheduler with BGProcessingTask Implementation: Sync data when device is charging Result: Data always synced, efficient battery usage

Troubleshooting

Problem 1: Tasks Don’t Run

Symptoms: Scheduled tasks never execute

Solutions: Check task registration, verify Info.plist configuration, test on real device, check task scheduling, verify app usage patterns

Problem 2: Tasks Expire Too Quickly

Symptoms: Tasks expire before completing

Solutions: Optimize task work, reduce work scope, use BGProcessingTask for longer tasks, batch operations

Problem 3: URLSession Not Completing

Symptoms: Background downloads/uploads don’t complete

Solutions: Check session configuration, verify delegate methods, check completion handler, verify app launch on completion

Problem 4: High Battery Usage

Symptoms: Background tasks drain battery

Solutions: Reduce task frequency, optimize task work, use efficient APIs, monitor execution time

Problem 5: Tasks Run Too Frequently

Symptoms: Tasks run more often than expected

Solutions: Adjust earliestBeginDate, cancel and reschedule, check task scheduling logic, verify no duplicate scheduling

Debugging Tips

Tip 1: Enable Background Task Logging

Add comprehensive logging:

func handleBackgroundFetch(task: BGAppRefreshTask) {
    print("🔄 Background fetch started at (Date())")

    task.expirationHandler = {
        print("⏰ Background fetch expired")
        task.setTaskCompleted(success: false)
    }

    fetchData { success in
        print("✅ Background fetch completed: (success) at (Date())")
        task.setTaskCompleted(success: success)
    }
}
func handleBackgroundFetch(task: BGAppRefreshTask) {
    print("🔄 Background fetch started at (Date())")

    task.expirationHandler = {
        print("⏰ Background fetch expired")
        task.setTaskCompleted(success: false)
    }

    fetchData { success in
        print("✅ Background fetch completed: (success) at (Date())")
        task.setTaskCompleted(success: success)
    }
}

Tip 2: Check Pending Tasks

Regularly check pending tasks:

func checkPendingTasks() {
    BGTaskScheduler.shared.getPendingTaskRequests { requests in
        print("📋 Pending tasks: (requests.count)")
        for request in requests {
            print("  - (request.identifier): (request.earliestBeginDate ?? Date.distantFuture)")
        }
    }
}
func checkPendingTasks() {
    BGTaskScheduler.shared.getPendingTaskRequests { requests in
        print("📋 Pending tasks: (requests.count)")
        for request in requests {
            print("  - (request.identifier): (request.earliestBeginDate ?? Date.distantFuture)")
        }
    }
}

Tip 3: Monitor Background Execution

Use System Trace in Instruments:

  1. Product → Profile → System Trace
  2. Record app
  3. Background app
  4. Check background execution
  5. Identify bottlenecks

Tip 4: Test Task Execution

Manually trigger tasks in debugger:

// In debugger, evaluate:
e -l objc -- (void)[[BGTaskScheduler sharedScheduler] _simulateLaunchForTaskWithIdentifier:@"com.yourapp.fetch"]
// In debugger, evaluate:
e -l objc -- (void)[[BGTaskScheduler sharedScheduler] _simulateLaunchForTaskWithIdentifier:@"com.yourapp.fetch"]

Best Practices Summary

API Selection

Quick cleanup (< 30s): beginBackgroundTask Scheduled content updates: BGTaskScheduler BGAppRefreshTask Scheduled data processing: BGTaskScheduler BGProcessingTask File downloads/uploads: URLSession background Special capabilities: Background modes

Implementation

Always schedule next task: BGTaskScheduler tasks run once Handle expiration: Set expiration handlers Call completion: Always call setTaskCompleted or endBackgroundTask Test on devices: Real devices show real behavior Monitor execution: Use logging and Instruments

Optimization

Minimize work: Do only essential work Batch operations: Process in batches Use efficient APIs: Choose right API Monitor battery: Track battery impact Optimize network: Batch requests, cache responses

Detailed Implementation Guide

Complete beginBackgroundTask Example

Here’s a complete example with error handling:

Void) {
// Perform save operation
DispatchQueue.global().async {
// Save data
let success = self.saveData()
DispatchQueue.main.async {
completion(success)
}
}
}

private func cleanup() {
// Cleanup if task expires
}

private func saveData() -> Bool {
// Save implementation
return true
}
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

class BackgroundSaveManager {
    private var backgroundTaskID: UIBackgroundTaskIdentifier = .invalid

    func saveDataWhenBackgrounded() {
        guard backgroundTaskID == .invalid else {
            print("Background task already running")
            return
        }

        backgroundTaskID = UIApplication.shared.beginBackgroundTask { [weak self] in
            guard let self = self else { return }
            print("Background task expired, cleaning up")
            self.cleanup()
            UIApplication.shared.endBackgroundTask(self.backgroundTaskID)
            self.backgroundTaskID = .invalid
        }

        guard backgroundTaskID != .invalid else {
            print("Failed to begin background task")
            return
        }

        performSave { [weak self] success in
            guard let self = self else { return }
            if success {
                print("Save completed successfully")
            } else {
                print("Save failed")
            }
            UIApplication.shared.endBackgroundTask(self.backgroundTaskID)
            self.backgroundTaskID = .invalid
        }
    }

    private func performSave(completion: @escaping (Bool) -> Void) {
        // Perform save operation
        DispatchQueue.global().async {
            // Save data
            let success = self.saveData()
            DispatchQueue.main.async {
                completion(success)
            }
        }
    }

    private func cleanup() {
        // Cleanup if task expires
    }

    private func saveData() -> Bool {
        // Save implementation
        return true
    }
}
class BackgroundSaveManager {
    private var backgroundTaskID: UIBackgroundTaskIdentifier = .invalid

    func saveDataWhenBackgrounded() {
        guard backgroundTaskID == .invalid else {
            print("Background task already running")
            return
        }

        backgroundTaskID = UIApplication.shared.beginBackgroundTask { [weak self] in
            guard let self = self else { return }
            print("Background task expired, cleaning up")
            self.cleanup()
            UIApplication.shared.endBackgroundTask(self.backgroundTaskID)
            self.backgroundTaskID = .invalid
        }

        guard backgroundTaskID != .invalid else {
            print("Failed to begin background task")
            return
        }

        performSave { [weak self] success in
            guard let self = self else { return }
            if success {
                print("Save completed successfully")
            } else {
                print("Save failed")
            }
            UIApplication.shared.endBackgroundTask(self.backgroundTaskID)
            self.backgroundTaskID = .invalid
        }
    }

    private func performSave(completion: @escaping (Bool) -> Void) {
        // Perform save operation
        DispatchQueue.global().async {
            // Save data
            let success = self.saveData()
            DispatchQueue.main.async {
                completion(success)
            }
        }
    }

    private func cleanup() {
        // Cleanup if task expires
    }

    private func saveData() -> Bool {
        // Save implementation
        return true
    }
}

Complete BGTaskScheduler Example

Here’s a complete BGTaskScheduler implementation:

Void) {
// Perform sync operation
syncData { success in
completion(success)
}
}

private func syncData(completion: @escaping (Bool) -> Void) {
// Sync implementation
completion(true)
}

private func cancelSync() {
// Cancel ongoing sync
}
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

class BackgroundSyncManager {
    private let taskIdentifier = "com.yourapp.background-sync"

    func setup() {
        BGTaskScheduler.shared.register(forTaskWithIdentifier: taskIdentifier, using: nil) { [weak self] task in
            guard let self = self else { return }
            self.handleBackgroundSync(task: task as! BGAppRefreshTask)
        }
    }

    func scheduleSync() {
        // Cancel existing task
        BGTaskScheduler.shared.cancel(taskRequestWithIdentifier: taskIdentifier)

        // Schedule new task
        let request = BGAppRefreshTaskRequest(identifier: taskIdentifier)
        request.earliestBeginDate = Date(timeIntervalSinceNow: 15 * 60) // 15 minutes

        do {
            try BGTaskScheduler.shared.submit(request)
            print("Background sync scheduled")
        } catch {
            print("Failed to schedule background sync: (error)")
        }
    }

    func handleBackgroundSync(task: BGAppRefreshTask) {
        print("Background sync started")

        // Schedule next sync
        scheduleSync()

        // Set expiration handler
        task.expirationHandler = { [weak self] in
            guard let self = self else { return }
            print("Background sync expired")
            self.cancelSync()
            task.setTaskCompleted(success: false)
        }

        // Perform sync
        performSync { [weak self] success in
            guard let self = self else { return }
            print("Background sync completed: (success)")
            task.setTaskCompleted(success: success)
        }
    }

    private func performSync(completion: @escaping (Bool) -> Void) {
        // Perform sync operation
        syncData { success in
            completion(success)
        }
    }

    private func syncData(completion: @escaping (Bool) -> Void) {
        // Sync implementation
        completion(true)
    }

    private func cancelSync() {
        // Cancel ongoing sync
    }
}
class BackgroundSyncManager {
    private let taskIdentifier = "com.yourapp.background-sync"

    func setup() {
        BGTaskScheduler.shared.register(forTaskWithIdentifier: taskIdentifier, using: nil) { [weak self] task in
            guard let self = self else { return }
            self.handleBackgroundSync(task: task as! BGAppRefreshTask)
        }
    }

    func scheduleSync() {
        // Cancel existing task
        BGTaskScheduler.shared.cancel(taskRequestWithIdentifier: taskIdentifier)

        // Schedule new task
        let request = BGAppRefreshTaskRequest(identifier: taskIdentifier)
        request.earliestBeginDate = Date(timeIntervalSinceNow: 15 * 60) // 15 minutes

        do {
            try BGTaskScheduler.shared.submit(request)
            print("Background sync scheduled")
        } catch {
            print("Failed to schedule background sync: (error)")
        }
    }

    func handleBackgroundSync(task: BGAppRefreshTask) {
        print("Background sync started")

        // Schedule next sync
        scheduleSync()

        // Set expiration handler
        task.expirationHandler = { [weak self] in
            guard let self = self else { return }
            print("Background sync expired")
            self.cancelSync()
            task.setTaskCompleted(success: false)
        }

        // Perform sync
        performSync { [weak self] success in
            guard let self = self else { return }
            print("Background sync completed: (success)")
            task.setTaskCompleted(success: success)
        }
    }

    private func performSync(completion: @escaping (Bool) -> Void) {
        // Perform sync operation
        syncData { success in
            completion(success)
        }
    }

    private func syncData(completion: @escaping (Bool) -> Void) {
        // Sync implementation
        completion(true)
    }

    private func cancelSync() {
        // Cancel ongoing sync
    }
}

Complete URLSession Background Example

Here’s a complete URLSession background download implementation:

Void)?
private var activeDownloads: [URL: URLSessionDownloadTask] = [:]

override init() {
super.init()
setupSession()
}

private func setupSession() {
let config = URLSessionConfiguration.background(withIdentifier: "com.yourapp.downloads")
config.isDiscretionary = false
config.sessionSendsLaunchEvents = true
config.allowsCellularAccess = true

urlSession = URLSession(configuration: config, delegate: self, delegateQueue: nil)
}

func download(url: URL) {
let task = urlSession.downloadTask(with: url)
activeDownloads[url] = task
task.resume()
print("Download started: (url)")
}

func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
guard let url = downloadTask.originalRequest?.url else { return }

print("Download completed: (url)")

// Move file from temporary location
let documentsPath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
let destinationURL = documentsPath.appendingPathComponent(url.lastPathComponent)

do {
try FileManager.default.moveItem(at: location, to: destinationURL)
print("File saved to: (destinationURL)")
} catch {
print("Failed to move file: (error)")
}

activeDownloads.removeValue(forKey: url)
}

func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
let progress = Double(totalBytesWritten) / Double(totalBytesExpectedToWrite)
print("Download progress: (Int(progress * 100))%")
}

func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
if let error = error {
print("Download failed: (error)")
}
}

func application(_ application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: @escaping () -> Void) {
print("Handling background URL session: (identifier)")
backgroundCompletionHandler = completionHandler

if urlSession == nil {
setupSession()
}
}

func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) {
print("Background URL session finished")
DispatchQueue.main.async { [weak self] in
self?.backgroundCompletionHandler?()
self?.backgroundCompletionHandler = nil
}
}
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

class BackgroundDownloadManager: NSObject, URLSessionDownloadDelegate {
    private var urlSession: URLSession!
    private var backgroundCompletionHandler: (() -> Void)?
    private var activeDownloads: [URL: URLSessionDownloadTask] = [:]

    override init() {
        super.init()
        setupSession()
    }

    private func setupSession() {
        let config = URLSessionConfiguration.background(withIdentifier: "com.yourapp.downloads")
        config.isDiscretionary = false
        config.sessionSendsLaunchEvents = true
        config.allowsCellularAccess = true

        urlSession = URLSession(configuration: config, delegate: self, delegateQueue: nil)
    }

    func download(url: URL) {
        let task = urlSession.downloadTask(with: url)
        activeDownloads[url] = task
        task.resume()
        print("Download started: (url)")
    }

    func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
        guard let url = downloadTask.originalRequest?.url else { return }

        print("Download completed: (url)")

        // Move file from temporary location
        let documentsPath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
        let destinationURL = documentsPath.appendingPathComponent(url.lastPathComponent)

        do {
            try FileManager.default.moveItem(at: location, to: destinationURL)
            print("File saved to: (destinationURL)")
        } catch {
            print("Failed to move file: (error)")
        }

        activeDownloads.removeValue(forKey: url)
    }

    func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
        let progress = Double(totalBytesWritten) / Double(totalBytesExpectedToWrite)
        print("Download progress: (Int(progress * 100))%")
    }

    func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
        if let error = error {
            print("Download failed: (error)")
        }
    }

    func application(_ application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: @escaping () -> Void) {
        print("Handling background URL session: (identifier)")
        backgroundCompletionHandler = completionHandler

        if urlSession == nil {
            setupSession()
        }
    }

    func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) {
        print("Background URL session finished")
        DispatchQueue.main.async { [weak self] in
            self?.backgroundCompletionHandler?()
            self?.backgroundCompletionHandler = nil
        }
    }
}
class BackgroundDownloadManager: NSObject, URLSessionDownloadDelegate {
    private var urlSession: URLSession!
    private var backgroundCompletionHandler: (() -> Void)?
    private var activeDownloads: [URL: URLSessionDownloadTask] = [:]

    override init() {
        super.init()
        setupSession()
    }

    private func setupSession() {
        let config = URLSessionConfiguration.background(withIdentifier: "com.yourapp.downloads")
        config.isDiscretionary = false
        config.sessionSendsLaunchEvents = true
        config.allowsCellularAccess = true

        urlSession = URLSession(configuration: config, delegate: self, delegateQueue: nil)
    }

    func download(url: URL) {
        let task = urlSession.downloadTask(with: url)
        activeDownloads[url] = task
        task.resume()
        print("Download started: (url)")
    }

    func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
        guard let url = downloadTask.originalRequest?.url else { return }

        print("Download completed: (url)")

        // Move file from temporary location
        let documentsPath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
        let destinationURL = documentsPath.appendingPathComponent(url.lastPathComponent)

        do {
            try FileManager.default.moveItem(at: location, to: destinationURL)
            print("File saved to: (destinationURL)")
        } catch {
            print("Failed to move file: (error)")
        }

        activeDownloads.removeValue(forKey: url)
    }

    func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
        let progress = Double(totalBytesWritten) / Double(totalBytesExpectedToWrite)
        print("Download progress: (Int(progress * 100))%")
    }

    func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
        if let error = error {
            print("Download failed: (error)")
        }
    }

    func application(_ application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: @escaping () -> Void) {
        print("Handling background URL session: (identifier)")
        backgroundCompletionHandler = completionHandler

        if urlSession == nil {
            setupSession()
        }
    }

    func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) {
        print("Background URL session finished")
        DispatchQueue.main.async { [weak self] in
            self?.backgroundCompletionHandler?()
            self?.backgroundCompletionHandler = nil
        }
    }
}

Background Task Patterns

Pattern 1: Retry Logic

Implement retry logic for failed background tasks:

<button data-code="class RetryableBackgroundTask {
private let maxRetries = 3
private var retryCount = 0

func handleBackgroundFetch(task: BGAppRefreshTask) {
scheduleBackgroundFetch()

task.expirationHandler = {
task.setTaskCompleted(success: false)
}

performTask { [weak self] success in
guard let self = self else { return }
if !success && self.retryCount

class RetryableBackgroundTask {
    private let maxRetries = 3
    private var retryCount = 0

    func handleBackgroundFetch(task: BGAppRefreshTask) {
        scheduleBackgroundFetch()

        task.expirationHandler = {
            task.setTaskCompleted(success: false)
        }

        performTask { [weak self] success in
            guard let self = self else { return }
            if !success && self.retryCount < self.maxRetries {
                self.retryCount += 1
                // Retry with exponential backoff
                let delay = pow(2.0, Double(self.retryCount)) * 60 // 2, 4, 8 minutes
                DispatchQueue.main.asyncAfter(deadline: .now() + delay) {
                    self.scheduleBackgroundFetch()
                }
            } else {
                self.retryCount = 0
            }
            task.setTaskCompleted(success: success)
        }
    }
}
class RetryableBackgroundTask {
    private let maxRetries = 3
    private var retryCount = 0

    func handleBackgroundFetch(task: BGAppRefreshTask) {
        scheduleBackgroundFetch()

        task.expirationHandler = {
            task.setTaskCompleted(success: false)
        }

        performTask { [weak self] success in
            guard let self = self else { return }
            if !success && self.retryCount < self.maxRetries {
                self.retryCount += 1
                // Retry with exponential backoff
                let delay = pow(2.0, Double(self.retryCount)) * 60 // 2, 4, 8 minutes
                DispatchQueue.main.asyncAfter(deadline: .now() + delay) {
                    self.scheduleBackgroundFetch()
                }
            } else {
                self.retryCount = 0
            }
            task.setTaskCompleted(success: success)
        }
    }
}

Pattern 2: Task Coordination

Coordinate multiple background tasks:

<button data-code="class TaskCoordinator {
private var activeTasks: Set = []

func scheduleTask(identifier: String) {
guard !activeTasks.contains(identifier) else {
print("Task already scheduled: (identifier)")
return
}

activeTasks.insert(identifier)
let request = BGAppRefreshTaskRequest(identifier: identifier)
request.earliestBeginDate = Date(timeIntervalSinceNow: 15 * 60)

try? BGTaskScheduler.shared.submit(request)
}

func taskCompleted(identifier: String) {
activeTasks.remove(identifier)
}
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

class TaskCoordinator {
    private var activeTasks: Set<String> = []

    func scheduleTask(identifier: String) {
        guard !activeTasks.contains(identifier) else {
            print("Task already scheduled: (identifier)")
            return
        }

        activeTasks.insert(identifier)
        let request = BGAppRefreshTaskRequest(identifier: identifier)
        request.earliestBeginDate = Date(timeIntervalSinceNow: 15 * 60)

        try? BGTaskScheduler.shared.submit(request)
    }

    func taskCompleted(identifier: String) {
        activeTasks.remove(identifier)
    }
}
class TaskCoordinator {
    private var activeTasks: Set<String> = []

    func scheduleTask(identifier: String) {
        guard !activeTasks.contains(identifier) else {
            print("Task already scheduled: (identifier)")
            return
        }

        activeTasks.insert(identifier)
        let request = BGAppRefreshTaskRequest(identifier: identifier)
        request.earliestBeginDate = Date(timeIntervalSinceNow: 15 * 60)

        try? BGTaskScheduler.shared.submit(request)
    }

    func taskCompleted(identifier: String) {
        activeTasks.remove(identifier)
    }
}

Pattern 3: Conditional Execution

Execute tasks conditionally based on app state:

Bool {
// Check conditions: network, battery, user preferences, etc.
return NetworkManager.shared.isConnected &&
UIDevice.current.batteryLevel > 0.2 &&
UserPreferences.shared.allowBackgroundSync
}
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

class ConditionalBackgroundTask {
    func handleBackgroundFetch(task: BGAppRefreshTask) {
        scheduleBackgroundFetch()

        // Check if task should run
        guard shouldRunTask() else {
            print("Task skipped due to conditions")
            task.setTaskCompleted(success: false)
            return
        }

        task.expirationHandler = {
            task.setTaskCompleted(success: false)
        }

        performTask { success in
            task.setTaskCompleted(success: success)
        }
    }

    private func shouldRunTask() -> Bool {
        // Check conditions: network, battery, user preferences, etc.
        return NetworkManager.shared.isConnected &&
               UIDevice.current.batteryLevel > 0.2 &&
               UserPreferences.shared.allowBackgroundSync
    }
}
class ConditionalBackgroundTask {
    func handleBackgroundFetch(task: BGAppRefreshTask) {
        scheduleBackgroundFetch()

        // Check if task should run
        guard shouldRunTask() else {
            print("Task skipped due to conditions")
            task.setTaskCompleted(success: false)
            return
        }

        task.expirationHandler = {
            task.setTaskCompleted(success: false)
        }

        performTask { success in
            task.setTaskCompleted(success: success)
        }
    }

    private func shouldRunTask() -> Bool {
        // Check conditions: network, battery, user preferences, etc.
        return NetworkManager.shared.isConnected &&
               UIDevice.current.batteryLevel > 0.2 &&
               UserPreferences.shared.allowBackgroundSync
    }
}

Common Questions

Q: How long can background tasks run?

A: beginBackgroundTask gives ~30 seconds. BGTaskScheduler tasks can run longer, but iOS decides when. URLSession downloads can run until complete.

Q: Why don’t my BGTaskScheduler tasks run?

A: iOS decides when to run them based on usage patterns. They may not run immediately. Test by triggering manually in debugger.

Q: Can I force background tasks to run?

A: No. iOS controls when background tasks run. You can only schedule them.

Q: Do background tasks work in simulator?

A: Limited. Test on real devices for accurate behavior.

Q: How do I debug background tasks?

A: Use logging, check task status, use Instruments System Trace, test on real devices.

Summary

Background tasks are complex but powerful. Choose the right API, implement it correctly, handle edge cases. Your background work will run reliably.

The Workflow:

  1. Choose the right API
  2. Implement correctly
  3. Schedule next task (if needed)
  4. Handle expiration
  5. Call completion handlers
  6. Test on real devices
  7. Monitor and debug

It’s that simple. Master background tasks. Make your app work in background.

Further reading:

iOS 26 Programming for Beginners is a clear, project-based path from zero to building apps with Swift 6 and Xcode 26. Mastering Swift 6 is the reference I point people to on concurrency, performance, and modern Swift patterns.

References

Thanks for Reading!

If this article helped you master background tasks, consider:

  • 👏 Clapping (up to 50 times) — it helps others find this article
  • 💬 Commenting — share your background task tips or questions
  • 🔔 Following — for more iOS development guides
  • 📤 Sharing — help other developers implement background tasks

Happy coding! 🚀